【问题标题】:How do I resolve a UnhandledPromiseRejectionWarning with Jest in node.js server如何在 node.js 服务器中使用 Jest 解决 UnhandledPromiseRejectionWarning
【发布时间】:2020-10-15 21:40:04
【问题描述】:

我的测试正常通过,但我不断收到 UnhandledPromiseRejectionWarning。关于如何解决这个问题的任何想法? 我尝试了很多解决方案,但似乎都没有。

node:32535) UnhandledPromiseRejectionWarning: Error: expect(received).toMatchObject(expected)

Matcher error: received value must be a non-null object

Received has value: undefined (node:32535) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:32535) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

这是我的测试文件:

jest.mock("./http");
const { fetchAllUsersData } = require("./http");

test("Data returned from server should be a list of users ", async () => {
  fetchAllUsersData()
    .catch((errorMessage) => expect(errorMessage).toThrowError(Error))
    .then((usersRetrieved) => {
      let users = usersRetrieved[0];
      let userModel = {
        id: 1,
        first_name: "Peggy",
        last_name: "Poppins",
        email: "mpoppins0@squidoo.com",
        ip_address: "192.54.212.191",
        latitude: 34.003135,
        longitude: -117.7228641222,
      };

      expect(users).toMatchObject(userModel);
    });
});

这是我在 mock 文件夹中的文件:

      const fetchAllUsersData = () => {
        return Promise.resolve({
          data: [
            {
              id: 1,
              first_name: "Merry",
              last_name: "Poppins",
              email: "mpoppins0@squidoo.com",
              ip_address: "192.54.212.191",
              latitude: 34.003135,
              longitude: -117.7228641,
            },
            {
              id: 15,
              first_name: "George",
              last_name: "Foreman",
              email: "gforeman@clear.com",
              ip_address: "12.564.124.521",
              latitude: 23.592254,
              longitude: 125.454227,
            },
          ],
        });
      };

      exports.fetchAllUsersData = fetchAllUsersData;

【问题讨论】:

    标签: javascript node.js express testing jestjs


    【解决方案1】:

    这个错误的原因是没有链接到从测试中返回的承诺。浮动承诺是一种反模式。 async..await 允许以比原始承诺所需的更少的纪律来实现这一点。将原始承诺与async 一起使用通常没有意义。此外,在同一个测试中同时测试成功和失败的请求是没有意义的,预期的响应应该是预先确定的。

    expect(errorMessage).toThrowError(Error) 仅在errorMessage 是一个同步抛出错误的函数时才有效。如果 fetchAllUsersData 拒绝 errorMessage 对象,它将无法按预期工作。

    它可能应该在一个测试中:

    test("...", async () => {
      const usersRetrieved = await fetchAllUsersData();
      ...
      expect(users).toMatchObject(userModel);
    });
    

    在另一个测试中:

    test("...", async () => {
      await expect(fetchAllUsersData()).rejects.toThrowError(Error);
    });
    

    此外,如果您测试__mock__ 中提供的您自己的测试代码,测试也不会起到很好的作用。他们应该测试生产代码。

    【讨论】:

    • 你好。谢谢你的建议。您的解决方案引发错误
    • 错误:expect(received).toMatchObject(expected) 匹配器错误:接收到的值必须是非空对象 接收到的值:未定义
    • 那是你建议的第一个测试
    • 如果断言正确,它不应该抛出错误。这部分在另一个已删除的答案中得到解决,它应该是usersRetrieved.data[0],因为usersRetrieved 不是数组和usersRetrieved[0] === undefined,它是“用户”,而不是“用户”。正如我所提到的,除了教育目的之外,您不需要测试自己的测试代码。
    • 不客气。实际测试可能会相似,但您需要模拟实际执行请求的事物(fetch、DB 等),而不是在专用于 fetchAllUsersData 的测试中使用它的事物(fetchAllUsersData)单位。
    猜你喜欢
    • 1970-01-01
    • 2019-12-18
    • 2017-10-20
    • 1970-01-01
    • 2021-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-22
    相关资源
    最近更新 更多