开玩笑的嘲笑和打字稿 [英] Jest mock and typescript

查看:57
本文介绍了开玩笑的嘲笑和打字稿的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为包装提取API的函数编写测试.

i am writing a test for a function that wraps the 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);
};

对于此功能的测试如下:

And the test for this function like this:

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');
});

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

The problem is that typescript does not recognize that fetch is mocked thus can not find mock property on window.fetch Here is the error:

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

我该如何解决?

推荐答案

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

You need to redefine window.fetch as a jest.Mock. For clarity it's better to define a different variable:

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的模拟移到测试之外以在以后恢复它.

Also consider moving the mocking of window.fetch outside the test to restore it afterwards.

这篇关于开玩笑的嘲笑和打字稿的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆