Search code examples
postgresqlnpmpostmanavakoa2

ava js test GET returns code 204 POSTMAN GET returns 200


I made some REST API endpoints using koa js 2 and postgres database.

I have a setup/teardown procedure which creates/drops a postgres database catalog (e.g. test_db) before running any tests. (I use npm script 'pretest' hook to do db setup and 'posttest' to do db teardown).

When I run the ava js tests, I have:

2 POST tests (insert 2 rows) - these both PASS
1 GET test (e.g. get /users/1) - FAIL: response code is 204 instead of 200
1 PUT test (e.g. POST /users/:id) - FAIL: response code is 204 instead of 200 .

I can run these tests against my dev config and they all pass

I don't understand how POST can succeed (a row was inserted to table) then the GET for the row that was just inserted returns 204 (no data).

Currently the test database teardown doesn't happen, so I can peek inside test database and verify that the POSTS did succeed, the rows were inserted with the correct ID values (as expected). (e.g. I can see a user with id==1 and a user with id==2) so calling the endpoint /users/1 or /users/2 should succeed when the test is executed.

If I launch my server using the test database, and run POSTMAN against these endpoints and the test database, everything works (e.g. GET /users/1 returns correctly and so does GET /users/2) I get json returned and a code of 200 instead of 204.

I don't understand why my ava tests would be getting code 204 when same call to POSTMAN returns code 200 and valid json response.

Any ideas on what could cause this?


Solution

  • found the solution - I did not seed database with seed data, and because of parallel nature of ava js tests, they were not occurring in sequential order.

    For example: I had 2 POSTs occurring, then a GET (from top to bottom)

    so there are 2 solutions to this:

    1. seed database with data as part of pre-test setup procedure (DML script)

    OR

    1. put a .before the 1st POST test to force POST to appear before GET

    test.before('POST user (CREATE)', async t => {

    instead of

    test('POST user (CREATE)', async t => {

    and then

    test('GET single user', async t => { t.plan(3)

    const res = await request(makeApp()) .get('/users/1')

    then you know your GET :id will succeed (because POST will be forced to occur prior to GET /users/:id (or GET /users/1)

    As ava js documentation says:

    "Having tests run concurrently forces you to write atomic tests, meaning tests don't depend on global state or the state of other tests, which is a great thing!"

    Hopefully this is helpful to a future user!