Skip to main content

How to add Authentication Data to a NestJS Integration Test Suite

Automatically

1. Pass Parameter to Test Method

The test suite can append the testsuite user token automatically be passing true as the second parameter to the test method.

./src/ItemModifier.spec.ts
it('should create', async () => {
const response = await testSuite.test(
{
method: 'POST',
url: `/some-url`,
},
true, // Pass `true` to the second parameter to indicate that the test should be authenticated
);

expect(response.statusCode).toEqual(201);
});

Manually

1. Create an Authentication Token

After your test suite has been set up, you can create an authentication token to use in your tests. This token will be used to authenticate requests to the API.

./src/ItemModifier.spec.ts
beforeEach(async () => {
controller = app.get(ItemModifierController);

const client = app.get<Client>(OidcClient);
tokenSet = await client.grant({
grant_type: 'client_credentials',
});
});

2. Inject Your Token into the Request

./src/ItemModifier.spec.ts
it('should create', async () => {
const response = await testSuite.test({
method: 'POST',
url: `/some-url`,
headers: {
authorization: `Bearer ${tokenSet.access_token}`, // Inject the token as a header
},
});

expect(response.statusCode).toEqual(201);
});