Search code examples
node.jsapiunit-testingjtest

Jest mockResolvedValue return undefined with multiple args


I am trying to write a unit test for my NodeJs code. I am mocking my API call by using mockResolvedValue.

This is my unit test:

const { search } = require("../src/utils");

jest.mock("axios");

test("Should find an user", async () => {
  axios.get.mockResolvedValue({
    data: [
      {
        userId: 1,
        name: "Mike",
      },
    ],
  });
  const phone = "123456789";
  const token = "ItIsAFakeToken"

  const name = await search(phone, token);
  expect(name).toEqual("Mike");
});

And this is my search function

const searchContact = async (phone, token) => {
  const config = {
    method: "get",
    url: "https://userdatabase/api/search",
    token,
    params: {
      phone
    },
  };
  const response = await axios(config);
  return response.name;
}

It returned me "undefined" of response, However, if I change my API call to the below code without using config parameter, I can get the expected data. The thing is I need to pass several args in the real code.

  const response = await axios.get("https://userdatabase/api/search");

Please help. Thank you.


Solution

  • I figured it out the reason.

    In my unit test file, I use axios.get.mockResolvedValue, it should be axios.mockResolvedValue (remove get). Since I don't use axios.get in the method which are tested.