赛普拉斯存根功能在加载我的应用程序后丢失

问题描述

在我的主要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 来解决这个问题 ;)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...