【问题标题】:How to mock fetch Response object如何模拟获取响应对象
【发布时间】:2021-02-15 07:25:30
【问题描述】:

我试图用 ts-jest 模拟 fetch 响应,但我遇到了 typescript 错误

import { mocked } from 'ts-jest/utils';
import fetch from 'node-fetch';

import { getInstallationAccessToken } from './index';

const mockedFetch = mocked(fetch, true);

describe('getInstallationAccessToken', () => {
  const TODAY = new Date();
  const TOMORROW = new Date();
  TOMORROW.setDate(TODAY.getDate() + 1);

  beforeEach(() => {
    mockedFetch.mockResolvedValue({
      status: 200,
      json: async () => ({
        token: 'MOCKED_GITHUB_INSTALLATION_ACCESS_TOKEN',
        expires_at: TOMORROW.toISOString()
      })
    });
    jest.clearAllMocks();
  });

  test('generates github app jwt token', async () => {
    await getInstallationAccessToken();
    expect(mockedJwt.sign).toBeCalledTimes(1);
  });
})

在此示例中,我收到以下错误:

Argument of type '{ status: number; json: () => Promise<{ token: string; expires_at: string; }>; }' is not assignable to parameter of type 'Promise<Response> | PromiseLike<Promise<Response>>'.
  Object literal may only specify known properties, and 'status' does not exist in type 'Promise<Response> | PromiseLike<Promise<Response>>'.ts(2345)

所以我尝试构造一个合适的Response 对象:

    const response = new Response(JSON.stringify({
      token: 'MOCKED_GITHUB_INSTALLATION_ACCESS_TOKEN',
      expires_at: TOMORROW.toISOString()
    }),  { status: 200 })


    mockedFetch.mockReturnValue(Promise.resolve(response));

但是现在,.json 方法没有在响应对象上定义

TypeError: response.json is not a function

      56 |     });
      57 |
    > 58 |     const json = await response.json();
         |                                 ^
      59 |
      60 |     if (response.status >= 300) {
      61 |       throw new Error(

关于如何解决这个问题的任何想法?

【问题讨论】:

    标签: typescript jestjs fetch response ts-jest


    【解决方案1】:

    我认为您可以再次尝试使用您的第一个模拟并将您的模拟对象转换为 Response 将按以下方式工作:

    
    import fetch, { Response } from 'node-fetch';
    
    
    mockedFetch.mockResolvedValue({
      status: 200,
      json: async () => ({
        token: 'MOCKED_GITHUB_INSTALLATION_ACCESS_TOKEN',
        expires_at: TOMORROW.toISOString()
      })
    } as Response); // cast to Response type since we just mock what we need to
    
    

    【讨论】:

    • 我试过了,打字稿要我先投射到unknown,但仍然抱怨Object literal may only specify known properties, and 'status' does not exist in type :(
    猜你喜欢
    • 1970-01-01
    • 2020-01-23
    • 1970-01-01
    • 2022-06-23
    • 2022-01-10
    • 2021-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多