typescript - 开 Jest 和 typescript

标签 typescript jestjs

我正在为包装获取 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 上找到模拟属性 这是错误:

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

我该如何解决这个问题?

最佳答案

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

  });

关于typescript - 开 Jest 和 typescript ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44180693/

相关文章:

Angular 2 - 无法解析 LoginService 的所有参数

angular - 将 http 响应映射到 typeScript 对象

javascript - 如何更改 Typescript 类的实例中的值?

javascript - axios请求抛出未知错误

javascript - 在单元测试中,如何测试具有对象参数的函数?

node.js - typescript 错误 TS2393 : Duplicate function implementation in a Node/Express app

reactjs - 将 React 别名为 preact 抛出无法找到模块 : 'react/jsx-runtime'

reactjs - "npm test"虽然测试成功但失败(使用 create-react-app 创建的 reactjs 应用程序)

jestjs - 如何配置 jest 在超过 x 秒时失败

reactjs - Enzyme/Jest onSubmit 不调用提交函数