prosource

Typescript 및 Jest를 사용한 단순 가져오기 모의

probook 2023. 6. 17. 09:27
반응형

Typescript 및 Jest를 사용한 단순 가져오기 모의

유형 스크립트를 사용하여 가져오기를 조롱하는 가장 쉬운 방법은 무엇입니까?

저는 아래와 같이 간단한 것을 하고 싶습니다.그러나 Typescript는 전체 가져오기 개체에 대한 정의와 일치하지 않는다고 말합니다.

Type 'Mock<Promise<{ json: () => Promise<{ test: number; }>; }>, []>' is not assignable to type '(input: RequestInfo, init?: RequestInit | undefined) => Promise<Response>'.
   Type 'Promise<{ json: () => Promise<{ test: number; }>; }>' is not assignable to type 'Promise<Response>'.
     Type '{ json: () => Promise<{ test: number; }>; }' is missing the following properties from type 'Response': headers, ok, redirected, status, and 11 more.

이 문제를 해결하기 위한 가장 간단한 해결책은 무엇일까요?실제로 전체 가져오기 개체 또는 다른 솔루션을 모의 실행하시겠습니까?

global.fetch = jest.fn(() =>
  Promise.resolve({
    json: () => Promise.resolve({ test: 100 }),
  }),
)

정의하고 있는 TypeScript를 말할 수 있습니다.global.fetch농담으로

global.fetch = jest.fn(() =>
  Promise.resolve({
    json: () => Promise.resolve({ test: 100 }),
  }),
) as jest.Mock;

이전 접근 방식을 사용하는 데 문제가 있었습니다. 이 문제를 해결하는 방법은 다음과 같습니다.

첫 번째 테스트 코드:

describe("Testing the Assets Service", () => {
let fetchMock: any = undefined;

beforeEach(() => {
    fetchMock = jest.spyOn(global, "fetch")
    .mockImplementation(assetsFetchMock);
});

afterEach(() => {
    jest.restoreAllMocks();
});

test('Fetch has been called', () => {
    const baseUrl = "https://myurl.com"
    fetchAssets(baseUrl);
    expect(fetchMock).toHaveBeenCalled();
    expect(fetchMock).toHaveBeenCalledWith(baseUrl);
}); 
});

fetchAsset 함수는 특정 URL을 사용하여 fetch 함수를 호출합니다.

이제 가져오기 동작을 조롱하는 함수:

export const assetsFetchMock = () => Promise.resolve({
ok: true,
status: 200,
json: async () => clientAssets
} as Response);

clientAssets는 제가 반환해야 하는 객체입니다. 반환해야 하는 객체 또는 기본 객체로 대체할 수 있습니다.

답변과 유사한 https://stackoverflow.com/a/64819545/19334273 을 사용할 수도 있습니다.

jest.spyOn(global, "fetch").mockImplementation( 
  jest.fn(
    () => Promise.resolve({ json: () => Promise.resolve({ data: 100 }), 
  }), 
) as jest.Mock ) 

댓글에서 Typescript와 Jest를 사용하여 간단한 fetch mock.

언급URL : https://stackoverflow.com/questions/64818305/simple-fetch-mock-using-typescript-and-jest

반응형