【问题标题】:Jest Mock not returning the mock data while writing Unit Test in reactJest Mock 在反应中编写单元测试时未返回模拟数据
【发布时间】:2021-09-24 00:58:40
【问题描述】:

我正在使用 fetch 调用 API 并为此编写测试用例。在进行 Fetch 调用时,我预计会模拟数据,但会收到 API 错误消息。

请帮助我了解它为什么不模拟数据。

使用 Jest、jest-fetch-mock 模块。代码如下

      const login = (username, password) => {
      return fetch('endpoint/login', () => {
        method: 'POST',
        body: JSON.stringify({
          data :{
            username,
            password
          }
        })
      })
      .then (res => res.json())
      .then (data => {
        if(data.response){
          return {
            response: "accessToken",
            error: null
          }
        }else{
          return {
            response: null,
            error: "Something went wrong"
          }
        }
      })
    }

现在我正在编写单元测试来测试这个 api,如下所示:-

     test("Auth Success Scenario", async () => {
      const onResponse = jest.fn();
      const onError = jest.fn();
      fetchMock.mockResponseONce(JSON.stringify({
        data: {
          response: "accessToken",
          error: null
        }
      }));

      return await AuthService.login("andy","password")
      .then(onResponse)
      .catch(onError)
      .finally( () => {
        console.log(onResponse.mock.calls[0][0]) // its return API error not mocked data
      })
    })

【问题讨论】:

标签: reactjs unit-testing jestjs jest-fetch-mock


【解决方案1】:

本来是要评论的,可惜我没有足够的声望。

您是否启用了文档 link 中指定的玩笑模拟

Create a setupJest file to setup the mock or add this to an existing setupFile. :
To setup for all tests


require('jest-fetch-mock').enableMocks()

Add the setupFile to your jest config in package.json:

"jest": {
  "automock": false,
  "setupFiles": [
    "./setupJest.js"
  ]
}

因为这似乎是唯一的情况,其中 fetch 将尝试对 API 进行实际调用,而不是给出模拟响应,从而导致失败。

您甚至可以为特定的测试文件启用模拟

import fetchMock from "jest-fetch-mock";
require('jest-fetch-mock').enableMocks();

【讨论】:

  • 感谢 Pushpendu,我已经按照您在上一个代码示例中提到的那样设置了 fetchMock。问题是我可以在我的测试文件中使用 fetchMock 但仍然无法模拟服务:(
  • 你能尝试在 fetch().then().then() 的末尾放置一个 catch 块吗?记录那里出现的任何错误。这可能有助于更好地理解问题
  • 然后它调用我的实际 API 并返回我定义的错误对象,即 { response: null, error: 'Error'}
  • 这可能看起来像是在黑暗中拍摄,但是您可以尝试为这个特定的测试文件启用 jest-fetch-mock 吗? require('jest-fetch-mock').enableMocks();就在您的导入语句下方
  • 所以我尝试了您的确切代码,唯一看起来不合适的是您应该检查 data.data.response 而不是 data.response 的 if 条件以返回 accesstoken 部分。除此之外,它对我来说非常有效。我将尝试在 stackblitz 上创建一个工作示例
猜你喜欢
  • 2020-05-25
  • 2018-12-28
  • 2018-07-28
  • 2020-03-02
  • 1970-01-01
  • 1970-01-01
  • 2020-02-11
  • 2015-07-10
  • 2017-05-14
相关资源
最近更新 更多