【问题标题】:Mock Axios multiple requests模拟 Axios 多个请求
【发布时间】:2019-05-06 15:38:35
【问题描述】:

所以我遇到了这个问题,我在componentDidMount 中发送了 4 到 5 个 API 调用,我想模拟一些响应以测试场景。这就是我的componentDidMount 的样子

  this.updateTokenHOC(this.getCommentsData)
  this.updateTokenHOC(this.checkReviewer)
  this.updateTokenHOC(this.getStepDataFromServer,1)
  this.updateTokenHOC(this.getStepDataFromServer,2)
  this.updateTokenHOC(this.getStepDataFromServer,3)
  this.updateTokenHOC(this.getStepDataFromServer,4)
  this.updateTokenHOC(this.getStepDataFromServer,5)

是的,这些都是 API 调用。 我尝试过使用axios-mock-adapter 模拟URL,Regex 请求。当我从测试环境进行axios 调用时,它会给我模拟响应。但是这些调用会改变状态,而我在我的状态中找不到。

测试未能模拟此调用。正如你所看到的调试我在状态中创建了测试属性

  getCommentsData(config) {
const type = this.state.viewType
const id = this.state.requestId
instance.get(`/review/sections?request_id=${id}&request_type=${type}`, config)
  .then((response) => {
    this.setState({test:'iam in comments data'})
    if (response.status === 200) {
      for (let step in response.data.sections) {
        if (response.data.sections[step].section_type === 'device_quota') {
          this.setState({
            ...this.state,
            steps: {
              ...this.state.steps,
              step1: {
                ...this.state.steps.step1,
                comments: response.data.sections[step].comments,
              },
            }
          })
        }

如果我可以像在酶 wrapper.find('ViewReview').instance() 中那样单独测试此方法,但也没有成功,则可以替代解决方案。

P.S 我试过NockJest-axios-mock(这可行,但对于多个请求我不能模拟所有的响应),moxios

【问题讨论】:

  • 所以状态没有像你期望的那样更新,是这个问题吗?如何更新状态,提供代码库
  • 实际上我无法像上面提到的那样模拟 axios 调用。因为这些调用是在没有任何操作的情况下进行的(如按钮单击、表单提交等)。
  • 你的 http 调用在 mount 时执行,你如何在 test 中挂载组件?
  • const wrapper = mount() 一旦挂载,所有的 API 调用都会被执行。我已经发布了我的答案。

标签: reactjs unit-testing axios jestjs enzyme


【解决方案1】:

好的,所以我找到了解决它的方法。

使用 jest-axios-mock。

所以它所做的就是堆叠你的调用。如果我在 ComponentDidMount 中有 4 个调用,并且我想模拟第二个 API 调用的响应,我将不得不这样做

 let FirstAPIcallMockResponse = {
   data: {
    "SomeData": [
      {
        "SomeProperty": SomeValue,
        "SomeProperty": SomeValue,
      }
    ]
  },
  status: 200
}
let fakeResponse = {
   data: {},
   status: 404
}
mockAxios.mockResponse(fakeResponse)
mockAxios.mockResponse(responseObj)
mockAxios.mockResponse(fakeResponse)
mockAxios.mockResponse(fakeResponse)

注意:假响应的状态应该是 404 或者在您的 API 调用正文中的其他内容,如果您没有条件 if(response.status===200),它将执行该部分

【讨论】:

    猜你喜欢
    • 2020-07-18
    • 1970-01-01
    • 2021-03-27
    • 1970-01-01
    • 2021-11-23
    • 2019-05-09
    • 2019-11-14
    • 2020-10-19
    • 2018-10-02
    相关资源
    最近更新 更多