Jest mock和打字稿

时间:2017-05-25 12:33:27

标签: typescript jestjs

我正在为包装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');
});

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

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

我怎么能解决这个问题?

2 个答案:

答案 0 :(得分:1)

您需要将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的模拟移出测试,以在以后恢复。

答案 1 :(得分:0)

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();

  });