adonisjs / auth

Official Authentication package for AdonisJS
https://docs.adonisjs.com/guides/auth/introduction
MIT License
187 stars 65 forks source link

Guard undefined in tests #220

Closed MANTENN closed 11 months ago

MANTENN commented 11 months ago
TypeError: client.get(...).guard is not a function

   at Object.executor tests/functional/user.spec.ts:19

Package version

^8.2.3

Node.js and npm version

v16.13.2 & 8.1.2

Sample Code (to reproduce the issue)

test.group('user route', () => {
  test('not authenticated', async ({ client }) => {
    const response = await client.get('protected-route')

    response.assertStatus(401)
    response.assertBodyContains({ "errors": [] })
  })

  test('authenticated', async ({ client }) => {
    // authenticate
    const user = await User.find(1)
    const response = await client.get('protected-route')
      .guard('web')
      .loginAs(user!)
    // ...
  })
});

default tests/bootstrap.ts file

import type { Config } from '@japa/runner'
import TestUtils from '@ioc:Adonis/Core/TestUtils'
import { assert, runFailedTests, specReporter, apiClient } from '@japa/preset-adonis'

export const plugins: Required<Config>['plugins'] = [assert(), runFailedTests(), apiClient()]

export const reporters: Required<Config>['reporters'] = [specReporter()]

export const runnerHooks: Pick<Required<Config>, 'setup' | 'teardown'> = {
  setup: [() => TestUtils.ace().loadCommands()],
  teardown: [],
}

export const configureSuite: Required<Config>['configureSuite'] = (suite) => {
  if (suite.name === 'functional') {
    suite.setup(() => TestUtils.httpServer().start())
  }
}

I believe this is the correct spot for opening the issue because the macro is defined here: https://github.com/adonisjs/auth/blob/49228c5b619ba76362ad8ccb2afc9e2f65e83104/src/Bindings/Tests.ts#L49, unless the preset plugin would make more sense: https://github.com/japa/preset-adonis/blob/develop/providers/TestsProvider/index.ts

MANTENN commented 11 months ago

Created a new repo and this issue is not present in it.

image
MANTENN commented 11 months ago

I assume its module resolution, not sure why its not resolving the auth test bindings.

image image
MANTENN commented 11 months ago
image
        this.application.container.withBindings(['Japa/Preset/ApiRequest', 'Japa/Preset/ApiClient', 'Adonis/Addons/Auth'], (ApiRequest, ApiClient, Auth) => {
            const { defineTestsBindings } = require('../src/Bindings/Tests');
            console.log('defineTestsBindings')
            return defineTestsBindings(ApiRequest, ApiClient, Auth);
        });

The callback passed into this.application.container.withBindings is not run.

MANTENN commented 11 months ago
image

Turns out one of the namespaces is missing a binding.

image
MANTENN commented 11 months ago
image

Same exact package version. In a new project, the condition resolves to true.

image
MANTENN commented 11 months ago

NODE_ENV=local was the root cause. didn't notice it in my test file.