supertest icon indicating copy to clipboard operation
supertest copied to clipboard

Using async, tests in series fail after first test run.

Open alexl0gan opened this issue 6 years ago • 1 comments

When defining a series of tests using async, the first test passes as expected but subsequent tests fail with 404.

describe("Test server ping", () => {

    let app: express.Application;

    beforeEach(() => {
        app = getApp();
    });

    it("should return pong", async () => {
        const res = await request(app).get("/ping");
        expect(res.status).toBe(200);
    });

    it("should reset", async () => {
        const res = await request(app).get("/reset");
        expect(res.status).toBe(205);
    });
});
 FAIL  test/integration/server/__tests__/pingpong.test.ts
  Test server ping
    ✓ should return pong (106ms)
    ✕ should reset (27ms)

  ● Test server ping › should reset

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

    Expected: 205
    Received: 404

      30 |         const res = await request(app).get("/reset");
    > 31 |         expect(res.status).toBe(205);
         |                            ^
      32 |     });
      33 |

      at Object.<anonymous> (test/integration/server/__tests__/pingpong.test.ts:31:28)
      at step (test/integration/server/__tests__/pingpong.test.ts:32:23)
      at Object.next (test/integration/server/__tests__/pingpong.test.ts:13:53)
      at fulfilled (test/integration/server/__tests__/pingpong.test.ts:4:58)

The same test series will pass using classic supertest expect. E.g.

it("should reset", async () => {
        request(app)
            .get("/reset")
            .expect(205);
});

Using jest with ts-node.

alexl0gan avatar Jan 24 '19 11:01 alexl0gan

@alexl0gan The reason the last example seems to be working, is because the test in not waiting for the async operation to complete. You could use the .end to wait for it using the classic interface, hopefully getting the same result as the first test.

it("should reset", (done) => {
        request(app)
            .get("/reset")
            .expect(205)
            .end((err, res) => {
               if (err) return done(err);
               done();
            });
});

As an alternative you could just return the expression:

it("should reset", () => {
        return request(app)
            .get("/reset")
            .expect(205);
});

jonathansamines avatar Jan 26 '19 03:01 jonathansamines