【问题标题】:Jest mock and typescript笑话模拟和打字稿
【发布时间】:2020-02-24 21:03:42
【问题描述】:

我正在为包装 fetch api 的函数编写测试。

const callAPI = (uri: string, options: RequestParams) => {

    let headers = { requestId: shortid.generate() };

    if (options.headers) {
        headers = { ...options.headers, ...headers};
    }

    const opts = {...options, ...{ headers }};
    return fetch(uri, opts);
};

这个函数的测试是这样的:

it('should add requestId to headers', () => {
    window.fetch = jest.fn();
    callAPI('localhost', { method: 'POST' });

    expect(window.fetch.mock.calls[0][1]).toHaveProperty('headers');
    expect(window.fetch.mock.calls[0][1].headers).toHaveProperty('requestId');
});

问题是打字稿无法识别 fetch 被模拟,因此无法在 window.fetch 上找到模拟属性 这是错误:

[ts] Property 'mock' does not exist on type '(input: RequestInfo, init?: RequestInit) => Promise<Response>'.

我该如何解决这个问题?

【问题讨论】:

  • 你在用 ts-jest 吗?
  • declare let global: { fetch: {} }; 并使用 global.fetch() 而不是 window.fetch()

标签: typescript jestjs


【解决方案1】:
it('test.', done => {
    const mockSuccessResponse = {YOUR_RESPONSE};
    const mockJsonPromise = Promise.resolve(mockSuccessResponse);
    const mockFetchPromise = Promise.resolve({
        json: () => mockJsonPromise,
    });
    var globalRef:any =global;
    globalRef.fetch = jest.fn().mockImplementation(() => mockFetchPromise);

    const wrapper = mount(
          <MyPage />,
    );

    done();

  });

【讨论】:

    【解决方案2】:

    您需要将window.fetch 重新定义为jest.Mock。为了清楚起见,最好定义一个不同的变量:

    it('should add requestId to headers', () => {
        const fakeFetch = jest.fn();
        window.fetch = fakeFetch;
        callAPI('localhost', { method: 'POST' });
        expect(fakeFetch.mock.calls[0][1]).toHaveProperty('headers');
        expect(fakeFetch.mock.calls[0][1].headers).toHaveProperty('requestId');
    });
    

    还可以考虑将 window.fetch 的模拟移到测试之外以在之后恢复它。

    【讨论】:

      猜你喜欢
      • 2018-12-15
      • 1970-01-01
      • 2020-12-19
      • 2019-02-06
      • 2017-12-10
      • 2020-08-08
      • 2018-06-21
      • 2019-09-13
      • 2018-09-16
      相关资源
      最近更新 更多