Testing HTTP POST request fails


#1

I want to test a POST request in AdonisJS.

I have two endpoints to test. One using the GET HTTP request to UserController.index(), the other to UserController.store(). The test to the later endpoint fails. A

Following are the involved parts in my code:

UserController.js:

'use strict'

class UserController {
  index() {
    return 'hi'
  }
  
  store() {
    return 'hi'
  }
}

module.exports = UserController

The model is the one that comes by default when installing AdonisJs.

factory.js:

const Factory = use('Factory')
const Hash = use('Hash')

Factory.blueprint('App/Models/User', async (faker) => {
  return {
    username: faker.username(),
    email: faker.email(),
    password: await Hash.make(faker.password())
  }
})

users.spec.js:

'use strict'

const { test, trait } = use('Test/Suite')('User')
const Factory = use('Factory')
trait('Test/ApiClient')

test('Route [GET] /users', async( { client } ) => {
  const response = await client
    .get('/users')
    .end()
  response.assertStatus(200)
})

test('Route [POST] /users/:id', async( { client } ) => {
  const user = Factory
    .model('App/Models/User')
    .create()
  let id = user.id
  const response = await client
    .post('users')
    .send(user)
  response.assertStatus(201)
})

I am getting this error message when I run the tests:

1. Route [POST] /users/:id
  TypeError: response.assertStatus is not a function
    at Callable.test [as _fn] (/home/begueradj/Development/draft/adonisjs-test-post-request/test/functional/users.spec.js:22:12)
    at processTicksAndRejections (internal/process/next_tick.js:81:5)

enter image description here

The POST test fails. Why? How to fix it?

Repository to reproduce. Follow the README instructions.

Thank you,
Billal BEGUERADJ


#2

Not in front of the computer to actual test this but I think you’re missing .end()

Unrelated: I think the “normal” endpoint for store should be a POST request to /users/ not /users/{id}


#3

Hey @begueradj! :wave:

As @pseudolog stated, the route you should use is /users and not /users/:id.

Also, I highly recommend you to check the tests of the Blog Demo we made. It might help you to understand how testing work.