问题描述
在我的主要React应用程序的类componentDidMount
中,我调用了api方法来获取一些数据。我正在测试给定数据,我的应用程序是否能正确执行操作。我不是尝试模拟服务器,也不使用赛普拉斯对fetch
的半支持,而是尝试cy.stub
整个API函数以返回一个数据块。
// api.ts
export const fetchData = async (): Promise<IData> => {
...
}
// app.tsx
import { fetchData } from "../api";
export class App extends React.PureComponent<IProps,IState> {
async componentDidMount() {
const data = await fetchData();
// ...
}
}
// testData.test.ts
import * as Api from "../../src/api";
context("Test the app after loading mock data from the API",() => {
describe("Calling the API",() => {
before(() => {
cy.stub(Api,"fetchData",() => {
return Promise.resolve({
someData: "value"
});
});
cy.visit("/");
});
it("calls 'fetchData'",() => {
expect(Api.fetchData).to.be.called;
});
});
});
但是,该应用仍会调用fetchData
的原始版本,而不是存根版本。
我尝试通过编写一个仅调用本身导入fetchData
的库方法的测试来进行试验,然后该模拟程序运行良好。因此,以这种方式模拟ES6函数应该可行。因此,这与加载导致丢失的应用程序有关。
解决方法
存根实际上不是这样工作的:
https://docs.cypress.io/guides/guides/network-requests.html#Stubbing
要开始添加响应,您需要做两件事。
启动cy.server() 提供一个cy.route()
cy.server() // enable response stubbing
cy.route({
method: 'GET',// Route all GET requests
url: '/users/*',// that have a URL that matches '/users/*'
response: [] // and force the response to be: []
})
不确定您要尝试执行哪个API调用,但这是一个很好的起点,并且不需要对您的内部api工作有任何了解。
不是很了解您要测试的内容,但是一个完整的例子是这样:
describe("Calling the API",() => {
cy.server() // enable response stubbing
cy.route({
method: 'GET',// Route all GET requests
url: '/users/*',// that have a URL that matches '/users/*'
response: [] // and force the response to be: []
})
.as('get-user')
.visit('/')
.wait('@get-user') // wait for your call to finish and assert it has been called
})
,
这在 cy.visit 中是不可能的。您可以使用新插件 @cypress/react 来解决这个问题 ;)