How can I authorize before to visit a page in a browser test?


#1

Here is an example of my test:

'use strict'

const { test, trait } = use('Test/Suite')('Admin/AuthController')

trait('Test/Browser')

test('/admin/logout', async ({ browser }) => {
  const page = await browser.visit('/admin/users')

  await page
    .click('a[href="/admin/logout"]')

  await page
    .assertPath('/admin/login')
}).timeout(0)

I want to test a page that is accessible only to an authorized user. How to do it?


#2

Use Session/Client and Auth/Client traits.

trait('Auth/Client')
trait('Session/Client')

and then use loginVia(user) method.

In docs https://adonisjs.com/docs/4.1/api-tests#_authentication


#3

Is not the loginVia(user) method intended only for the http tests?

I corrected my test as follows:

'use strict'

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

trait('Test/Browser')
trait('Auth/Client')
trait('Session/Client')

test('/admin/logout', async ({ browser }) => {
  const admin = await Admin.find(1)
  
  const page = await browser
    .loginVia(admin, 'sessionAdmin')
    .visit('/admin/users')

  await page
    .click('a[href="/admin/logout"]')

  await page
    .assertPath('/admin/login')
}).timeout(0)

But when I run this test, I get a “TypeError: browser.loginVia is not a function” error.