微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用 NodeJS 解决 Supertest 和 jest 中的 ECONNREFUSED 错误?

如何解决如何使用 NodeJS 解决 Supertest 和 jest 中的 ECONNREFUSED 错误?

我正在使用 Jest、Supertest 和 Mongoose 作为端点,使用 MongoDB 在 NodeJS 中编写后端项目的测试用例。目前我遇到错误 UnhandledPromiseRejectionWarning: Error: connect ECONNREFUSED 127.0.0.1:60524 并且测试失败。下面的代码是用异步方法编写的,它给出了我预期的实际结果。如果我用 then().catch() 编写相同的逻辑,则没有错误,它显示一切正常,即使它应该是失败的测试用例。

#gen.test.js

const request = require("supertest");
let server;
const { Genres } = require("../../models/genres");

describe("/api/genres",() => {
  beforeEach(() => {
    server = require("../../index");
  });

  afterEach(() => {
    server.close();
    Genres.deleteMany({}).then((res) =>
      winston.info(`Deleted Documents ${res.deletedCount}.`)
    );
  });

  describe("GET /",() => {
    it("should return all the genres.",async () => {
      await Genres.collection.insertMany([
        { name: "genre1" },{ name: "genre2" },{ name: "genre3" },]);

      const res = await request(server).get("/api/genres");
      expect(res.status).toBe(200);
      expect(res.body.length).toBe(3);
      expect(res.body.some((g) => g.name === "genre1")).toBeTruthy();

      
    });

  });

    //This one works with then().cath() . But If I make this to something that I don't expect,It still works.

   describe("GET /id",() => {
    it("should return a single genre",() => {
      const genre = new Genres({ name: "genre1" });
      genre
        .save()
        .then((res) => winston.info("new genre is saved for /id search"))
        .catch((err) => winston.error(err.message));

      request(server)
        .get("/api/genres/" + genre._id)
        .then((res) => {
          expect(res.status).toBe(200);
          expect(res.body).toHaveProperty("name",genre.name);
        });
    });
});

我从 Jest 那里得到的错误

 ● /api/genres › GET / › should return all the genres.

    expect(received).toBe(expected) // Object.is equality

    Expected: 200
    Received: 500

      26 |
      27 |       const res = await request(server).get("/api/genres");
    > 28 |       expect(res.status).toBe(200);
         |                          ^
      29 |       expect(res.body.length).toBe(3);
      30 |       expect(res.body.some((g) => g.name === "genre1")).toBeTruthy();
      31 |

      at Object.<anonymous> (tests/integration/genres.test.js:28:26)

和 UnhandledPromiseRejectionWarning 错误重复出现。

(node:31169) UnhandledPromiseRejectionWarning: Error: connect ECONNREFUSED 127.0.0.1:60524
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1141:16)
(node:31169) 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:31169) [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.
(node:31169) UnhandledPromiseRejectionWarning: Error: connect ECONNREFUSED 127.0.0.1:60525
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1141:16)
(node:31169) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block,use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:31169) UnhandledPromiseRejectionWarning: Error: connect ECONNREFUSED 127.0.0.1:60528
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1141:16)
(node:31169) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block,use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 3)
(node:31169) UnhandledPromiseRejectionWarning: Error: connect ECONNREFUSED 127.0.0.1:60529
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1141:16)
(node:31169) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block,use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 4)
A worker process has Failed to exit gracefully and has been force exited. This is likely caused by tests leaking due to improper teardown. Try running with --detectOpenHandles to find leaks.

我一直在对此进行研究以解决错误。我该如何解决这个问题?

解决方法

在 routes 文件夹中检查您的风格.js 并删除该行: throw new Error('找不到类型!'); --- 删除这个

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。