본문 바로가기
All Side/Runtime > NodeJS

[Jest] Axios undefined 해결하기 with.mock

by developerBeluga 2022. 9. 14.
728x90
반응형

 

 

 

 

Axios로 통신하여 데이터를 잘 가져오는지 확인하기 위해 테스트 코드를 작성했다.

하지만 예상과 달리 결과값이 undefined였다.

 

공식문서를 확인해보니 axios를 테스트하기 위해서는 jest.mock를 써줘야했다.

공식문서 : https://jestjs.io/docs/mock-functions#mocking-modules

 

Mock Functions · Jest

Mock functions allow you to test the links between code by erasing the actual implementation of a function, capturing calls to the function (and the parameters passed in those calls), capturing instances of constructor functions when instantiated with new,

jestjs.io

하지만 공식문서에 나온 예시를 참고하여 코드를 변경해도 똑같이 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
반응형

댓글