在我的主 React 应用程序的类中,componentDidMount
我调用 api 方法来获取一些数据。我正在尝试测试我的应用程序在给定数据的情况下是否执行正确的操作。我没有尝试模拟服务器,也没有处理 Cypress 的半支持之fetch
类的问题,而是尝试让cy.stub
整个 API 函数只返回一个数据块。
// api.ts
export const fetchData = async (): Promise<IData> => {
...
}
Run Code Online (Sandbox Code Playgroud)
// app.tsx
import { fetchData } from "../api";
export class App extends React.PureComponent<IProps, IState> {
async componentDidMount() {
const data = await fetchData();
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
// 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;
});
});
});
Run Code Online (Sandbox Code Playgroud)
但是,该应用程序仍然调用原始版本fetchData
而不是存根版本。
我尝试通过编写一个测试来进行实验,该测试只需调用一个本身导入的库方法fetchData
,这次模拟工作得很好。所以以这种方式模拟 ES6 函数应该可行。因此,这与加载我的应用程序有关,导致它丢失。
Arc*_*rus -1
这并不是存根应该如何工作的:
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: []
})
Run Code Online (Sandbox Code Playgroud)
不确定您要尝试执行哪个 API 调用,但这是一个很好的开始,并且不需要 cypress 了解您的内部 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
})
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2995 次 |
最近记录: |