TypeScript × Jest로 axios의 모의 만들기 테스트를 실시한다
8760 단어 testJestMockTypeScriptaxios
소개
TypeScript에서 Jest의 모의 기능을 사용하려고하면 빠졌습니다. . .
해결 방법을 찾았으므로 메모합니다.
대상 독자
환경
테스트 대상
출처
src/index.ts
import axios from 'axios';
export async function main() {
try {
const { data } = await axios.get('{YOUR-API-ENDPOINT}');
return data; // { message: "Real response!" }
} catch (err) {
throw new Error(err.message);
}
}
main().then(res => console.log(res));
실행 결과
$ npx tsc
$ node dist/index.js
{ message: 'Real response!' }

테스트 코드
쓰기 1
test/index.test.ts
jest.mock('axios');
import axios from 'axios';
// tslint:disable-next-line:no-any
(axios.get as any).mockResolvedValue({ data: { message: 'Mock response!!!' } });
import { main } from '../src/index';
describe('main test', () => {
it('axios return mock value', async () => {
const res = await main();
expect(res.message).toBe('Mock response!!!');
});
});
쓰기 2
test/index.test.ts
jest.mock('axios');
import axios, { AxiosInstance } from 'axios';
// tslint:disable-next-line:no-any
const myAxios: jest.Mocked<AxiosInstance> = axios as any;
myAxios.get.mockResolvedValue({ data: { message: 'Mock response!!!' } });
import { main } from '../src/index';
describe('main test', () => {
it('axios return mock value', async () => {
const res = await main();
expect(res.message).toBe('Mock response!!!');
});
});
테스트 실행 결과

결론
쓰는 방법의 1과 2를 비교했을 경우, 문자수가 적게 되는 것은 1입니다만, 2의 경우는 위의 예로 말하면
myAxios 있습니다.1의 경우는
mockResolvedValue()를 수동으로 기입할 필요가 있습니다만, 2의 경우는 IDE의 예측으로 나옵니다.코딩 실수를 줄이기 위해서도 자신은 2 를 사용해 갈까라고 생각하고 있습니다.
any형을 사용하지 않고 쓸 수 있는 방법을 알고 싶다. . .
2019/07/23 추가
@Statham 씨에게 코멘트로 any 형을 사용하지 않는 쓰는 법을 가르쳐 주셨습니다! 감사합니다!
Reference
이 문제에 관하여(TypeScript × Jest로 axios의 모의 만들기 테스트를 실시한다), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://qiita.com/rema424/items/ee650a1cf99de178cb90텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)