【问题标题】:Using Jest even after doing fetch.mockResponse actual fetch is getting called即使在执行 fetch.mockResponse 之后使用 Jest 实际 fetch 也被调用
【发布时间】:2019-06-10 03:52:35
【问题描述】:

我不熟悉反应并尝试使用 Jest 编写我的第一个测试用例。我必须模拟一个 fetch 响应。我正在使用 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)那么如何模拟它? 提前致谢!

【问题讨论】:

    标签: reactjs jestjs jest-fetch-mock


    【解决方案1】:

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

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

    另请注意,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... */);
    });
    

    【讨论】:

      猜你喜欢
      • 2021-08-14
      • 2017-10-19
      • 2016-12-25
      • 2022-01-25
      • 1970-01-01
      • 1970-01-01
      • 2016-10-11
      • 1970-01-01
      • 2014-03-18
      相关资源
      最近更新 更多