Jest mockResolvedValue 返回未定义的多个参数

时间:2021-01-11 20:48:54

标签: node.js api unit-testing jtest

我正在尝试为我的 NodeJs 代码编写单元测试。我正在使用 mockResolvedValue 来模拟我的 API 调用。

这是我的单元测试:

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");
});

这是我的 search 函数

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;
}

它返回了“undefined”响应,但是,如果我将 API 调用更改为以下代码而不使用 config 参数,我可以获得预期的数据。问题是我需要在实际代码中传递几个参数。

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

请帮忙。谢谢。

1 个答案:

答案 0 :(得分:1)

我找到了原因。

在我的单元测试文件中,我使用 axios.get.mockResolvedValue,它应该是 axios.mockResolvedValue(删除 get)。因为我在测试的方法中没有使用 axios.get