Include / use csrfToken When Testing RestAPI


#1

Hi All,

after creating some sample rest API in adonisjs ver 4.1, now i am working on testing phase. obviously i all my test work properly if i disable the csrf protection. but when i enable it, it doesn’t work well for certain method ( i.e post, put etc…)

what i need is, how can i include / put csrfToken into my test file?

here is some of my test suite command :

'use strict'

const {test, trait} = use('Test/Suite')('Todo')
const Todos         = use('App/Models/Todos')

trait('Test/ApiClient')

test('call create with empty data shall return 404', async ({client}) => {
  const response = await client.post('/todo/create').send({}).end()
  response.assertStatus(404)
}).timeout(0)

i am expecting 404 but it returning 403 due to csrf protection. I don’t want to disable the csrf protection because i intend to build a SPA with reactJs after this.

can anyone help me to make the test work properly with csrfToken included in my test case ?

please help, thank you very much


#2

after done a lot of searching on google, got some suggestion from friends, i’ve decided to just disable the csrf protection while testing. so i made some update on my config/shield.js file, here is some changes i made :

  csrf: {
    enable       : process.env.NODE_ENV === 'testing' ? false : true,
    methods      : ['POST', 'PUT', 'DELETE', 'PATCH'],
    filterUris   : [],
    cookieOptions: {
      httpOnly: false,
      sameSite: true,
      path    : '/',
      maxAge  : 7200
    }
  }

i put this line : process.env.NODE_ENV === 'testing' ? false : true on enable key. it tells the middleware to just disable if NODE_ENV equals to ‘testing’.

i think problem is solve now, and this is the better way to do it.

thanks anyway for everyone