tezvyn:

Integration testing a POST endpoint with Supertest

AI-drafted, machine-checkedSource: interviewintermediate
WHAT IT TESTS

HTTP-level integration testing.

OUTLINE

pass the Express app to supertest, send a POST with a body, then assert status 201, the response shape, and the persisted side effect; also test validation failures.

WHAT THIS TESTS Whether you can drive an Express endpoint through real HTTP and assert both the response and the persisted effect, including failure paths.

A GOOD ANSWER COVERS Supertest wraps your Express app object directly, so you import the app (exported without calling listen, or it lets Supertest manage an ephemeral port) and call request(app).post('/users').send(body). You await the result and make several assertions. First the status code: a successful create should return 201 Created. Second the response body: assert it contains the created resource with the expected fields, and confirm sensitive fields like the password hash are not returned. Third the side effect: query the test database to confirm the user was actually persisted, which is what makes this an integration test rather than a pure handler test. You should also write negative cases: posting invalid or missing fields and asserting a 400 with a useful error body, and posting a duplicate and asserting 409. Use a fresh or transactionally rolled-back test database so tests stay independent.

COMMON WRONG ANSWERS Asserting only the status code and nothing else, returning the password in the response, running against production, or leaving state between tests so they interfere.

LIKELY FOLLOW-UPS Why you test the DB side effect, isolating test data, mocking external services, and testing auth-protected routes with a token.

ONE CONCRETE EXAMPLE const res = await request(app).post('/users').send({ email: 'a@b.com', password: 'secret123' }); expect(res.status).toBe(201); expect(res.body.email).toBe('a@b.com'); expect(res.body.password).toBeUndefined(); const inDb = await User.findOne({ email: 'a@b.com' }); expect(inDb).not.toBeNull(); This checks the status, the response shape, the absence of the password, and the actual persistence.

Read the original → github.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.