当尝试使用 fetch 在 Cypress IO (JS) 中针对 React 应用存根请求时,请求仍会调用服务器
When attempting to stub a request in Cypress IO (JS) against a React app using fetch, the requests still call through to the server
我正在使用 Cypress 为我的 React 应用创建一些规范。我的 React 应用程序使用 fetch 从外部 api (isomorphic-fetch)
获取数据
我的应用中的获取请求是这样的
import fetch from 'fetch'
...
fetch('http://www.external-server.com/ideas.json')
.then((response) => {
if (response.status >= 400) {
}
return response.json().then((result) => {
this._data = result
this._data((ele) => ele.key = ele.id)
});
})
在我的 Cypress 规范中,我希望我的常规规范点击我的 lcoahost:3000 以获得初始页面(其中包含我的 React 应用程序)。我的 React 应用程序通常会发出外部请求 (http://www.external-server.com/ideas.json),但在我的规范中,我想删除该请求并仅在我的规范中包含该端点 return 虚假数据。
The Cypress docs for cy.route() here,描述我应该能够做类似
的事情
cy.server()
cy.route('http://www.external-server.com/ideas.json', [
{
id: 1,
name: 'john'
}
])
我试图在我的规范上下文中将其放入 运行 的 beforeEach 中(因此 运行ning 在每个规范之前)。
您会注意到,当我 运行 Cypress 测试 运行ning 中的规范时,控制台输出中显示端点 应该 是存根。
但是,通过检查,我可以看到我的应用程序实际上正在向真实服务器发出请求,并调用真实端点(而不是存根)。
我测试了几次,我确定这是行为。
我在网上找到了解决方案我会在下面post回答我的问题
解决方案已添加到 cypress/support/commands.js
这个小 hack 会将 window 提取变成空操作(禁用它),并允许 Cypress 中的本机存根工作而无需任何更改。
Cypress.Commands.overwrite('visit', (originalFn, url, options) => {
const opts = Object.assign({}, options = {}, {
onBeforeLoad: (window, ...args) => {
window.fetch = null;
if (options.onBeforeLoad) {
return options.onBeforeLoad(window, ...args);
}
},
});
return originalFn(url, opts);
});
我正在使用 Cypress 为我的 React 应用创建一些规范。我的 React 应用程序使用 fetch 从外部 api (isomorphic-fetch)
获取数据我的应用中的获取请求是这样的
import fetch from 'fetch'
...
fetch('http://www.external-server.com/ideas.json')
.then((response) => {
if (response.status >= 400) {
}
return response.json().then((result) => {
this._data = result
this._data((ele) => ele.key = ele.id)
});
})
在我的 Cypress 规范中,我希望我的常规规范点击我的 lcoahost:3000 以获得初始页面(其中包含我的 React 应用程序)。我的 React 应用程序通常会发出外部请求 (http://www.external-server.com/ideas.json),但在我的规范中,我想删除该请求并仅在我的规范中包含该端点 return 虚假数据。
The Cypress docs for cy.route() here,描述我应该能够做类似
的事情cy.server()
cy.route('http://www.external-server.com/ideas.json', [
{
id: 1,
name: 'john'
}
])
我试图在我的规范上下文中将其放入 运行 的 beforeEach 中(因此 运行ning 在每个规范之前)。
您会注意到,当我 运行 Cypress 测试 运行ning 中的规范时,控制台输出中显示端点 应该 是存根。
但是,通过检查,我可以看到我的应用程序实际上正在向真实服务器发出请求,并调用真实端点(而不是存根)。
我测试了几次,我确定这是行为。
我在网上找到了解决方案我会在下面post回答我的问题
解决方案已添加到 cypress/support/commands.js
这个小 hack 会将 window 提取变成空操作(禁用它),并允许 Cypress 中的本机存根工作而无需任何更改。
Cypress.Commands.overwrite('visit', (originalFn, url, options) => {
const opts = Object.assign({}, options = {}, {
onBeforeLoad: (window, ...args) => {
window.fetch = null;
if (options.onBeforeLoad) {
return options.onBeforeLoad(window, ...args);
}
},
});
return originalFn(url, opts);
});