728x90
반응형
Axios로 통신하여 데이터를 잘 가져오는지 확인하기 위해 테스트 코드를 작성했다.
하지만 예상과 달리 결과값이 undefined였다.
공식문서를 확인해보니 axios를 테스트하기 위해서는 jest.mock를 써줘야했다.
공식문서 : https://jestjs.io/docs/mock-functions#mocking-modules
하지만 공식문서에 나온 예시를 참고하여 코드를 변경해도 똑같이 undefined가 나왔다.
여러번 시도한 끝에 테스트에 성공할 수 있었다.
아래는 전체 코드이다.
// dbRead.ts
import axios from "axios";
export const reads = async() => {
let res = await axios.post("http://localhost:3999/v1/query/read", {
library: "6ab594e00998677474f2f699c2f993cd6404f934",
query: "",
})
return res.data
}
// read.test.ts
import { reads } from "../apps/dbRead";
import axios from 'axios';
jest.mock('axios');
test("Axios 통신에 성공하여 read 해오는가?", () => {
const readData = [{ data: { num: 1 }, lastUpdateDate: '2022-09-01T08:53:25.065Z' }, { data: { num: 2 }, lastUpdateDate: '2022-09-01T08:53:25.065Z]' }];
const resp = { data: readData };
(axios.post as jest.Mock).mockImplementation(() => Promise.resolve(resp));
return reads().then(resp => expect(resp).toEqual(readData));
})
원인은 mockResolvedValue 때문이었다.
공식문서를 보면 mockResolvedValue를 이용해서 가짜 비동기 함수를 만들었다.
하지만 아무리 해봐도 결과 값은 undefined가 나올 뿐이었다.
여러번의 시도 끝에 mockResolvedValue 대신 mockImplementation을 쓰면 된다는 것을 알았다.
mockImplementation는 아예 해당 함수를 통째로 즉석해서 재구현할 수 있게 해준다.
728x90
반응형
'All Side > Runtime > NodeJS' 카테고리의 다른 글
[Error] Sharp - Error: Input file is missing / Error: Input buffer contains unsupported image format + Axios로 파일 통신 받을 때 생기는 오류 (0) | 2022.12.02 |
---|---|
Express에서 로그인 서비스 만드는 방법 with.Session (0) | 2022.10.12 |
[NodeJS] code ERESOLVE ERESOLVE could not resolve 해결 (0) | 2022.08.30 |
[NodeJS] 테스트 코드 작성하기 (1) 알아버린 참맛 + 필요성 (0) | 2022.08.24 |
[NodeJS] 검색기능 만들기 (1) MongoDB Query (0) | 2022.08.19 |
댓글