reactjs - 即使在执行 fetch.mockResponse 之后仍使用 Jest 实际获取被调用

标签 reactjs jestjs jest-fetch-mock

我是 React 新手,正在尝试使用 Jest 编写我的第一个测试用例。我必须模拟获取响应。我正在使用 jest-fetch-mock。但调用将进行实际提取,返回的数据未定义。

package.json :

“jest-fetch-mock”:“^2.1.2”


setupTest.js 文件

global.fetch = require('jest-fetch-mock');

实际的api调用方式:

static fetchUserInfo(){
    return dispatch => {
        fetch('https://localhost:55001/api/userInfo')
            .then(this.httpResponseHandler.handleHttpResponse)
            .then ((resp) => resp.json())
            .then(data => dispatch(this.onUserInfoGetSuccess(data)))
            .catch( error => {
                dispatch(this.onFetchFailure(error));
            });
    };
}

测试用例

it('should get user info', () => {
    fetch.mockResponse(JSON.stringify({
            "name": "swati joshi",
        }
    ));

    let data = ActualDataApi.fetchUserInfo();
    console.log(data);
    expect(data.name).toEqual('swati joshi');
}

因为 fetchUserInfo 是调度程序(使用 Redux 和 React)那么如何模拟它? 提前致谢!

最佳答案

fetch 可能未正确模拟...但看起来您的主要问题是 fetchUserInfo 返回一个函数

应该在 dispatch mock 上调用它返回的函数,以验证它是否派发了正确的操作。

另请注意,fetchUserInfo 返回的函数是异步的,因此您需要一种方法在测试期间等待它完成。

如果您修改 fetchUserInfo 返回的函数以返回 Promise,如下所示:

static fetchUserInfo(){
  return dispatch => {
    return fetch('https://localhost:55001/api/userInfo')  // <= return the Promise
      .then(this.httpResponseHandler.handleHttpResponse)
      .then((resp) => resp.json())
      .then(data => dispatch(this.onUserInfoGetSuccess(data)))
      .catch(error => {
        dispatch(this.onFetchFailure(error));
      });
  };
}

...然后你可以这样测试它:

it('should get user info', async () => {  // <= async test function
  fetch.mockResponse(JSON.stringify({
    "name": "swati joshi",
  }));

  let func = ActualDataApi.fetchUserInfo();  // <= get the function returned by fetchUserInfo
  const dispatch = jest.fn();
  await func(dispatch);  // <= await the Promise returned by the function
  expect(dispatch).toHaveBeenCalledWith(/* ...the expected action... */);
});

关于reactjs - 即使在执行 fetch.mockResponse 之后仍使用 Jest 实际获取被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56520314/

相关文章:

reactjs - 无效的 Chai 属性 : toMatchSnapshot -- React. js Jest 测试

javascript - Jest 模拟第三方对象

reactjs - 如何测试子组件是否已呈现?

continuous-integration - TeamCity 上的 Jest 测试

jestjs - jest.mock(..) 在 'describe' 中不起作用(TypeError : moduleName. split is not a function)

reactjs - react Jest : trigger 'addEventListener' 'message' from tests

javascript - 我应该检查哪种 Prop 类型以获取来源?

javascript - 在 React-Select 中禁用关注第一个选项

javascript - 如何监视对于Jest方式导入的函数

unit-testing - 如何对不存在的外部依赖进行开 Jest