How to use async/await with chai test?

319 Views Asked by At

I have a chai test that works without async/await syntax, but crashes with it. How to fix it?

The error is:

error Error [ERR_SERVER_ALREADY_LISTEN]: Listen method has been called more than once without closing. code: 'ERR_SERVER_ALREADY_LISTEN'

Here is the same test with a working classic syntax and a non-working async/await syntax:

chai.use(chaiHttp);
const api = chai.request(server).keepOpen();

// async/await => doesn't work
describe("GET /user/:id", () => {
  it("return user information", async (done) => {
    const res = await api
      .get("/user/123")
      .set("Cookie", "_id=567;locale=en");
    chai.expect(res.status).to.equal(200);
    done();
  });
});

// classic syntax => works
describe("GET /user/:id", () => {
  it("return user information", () => {
    api
      .get("/user/123")
      .set("Cookie", "_id=567;locale=en")
      .end(function (err, res) {
        chai.expect(res).to.have.status(200);
      });
  });
});

0

There are 0 best solutions below