반응형
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
반응형
'prosource' 카테고리의 다른 글
에서 암시적 애니메이션 사용 안 함 -[CALayer setNeedsDisplayInRect:] (0) | 2023.06.17 |
---|---|
장고: 로그인 후 이전 페이지로 리디렉션 (0) | 2023.06.17 |
C - scanf() vs gets() vs fgets() (0) | 2023.06.17 |
VBA, 문자열에 특정 문자가 포함된 경우 (0) | 2023.06.12 |
개별 Python 장치 테스트를 일시적으로 사용하지 않도록 설정 (0) | 2023.06.12 |