In this blog, we'll explore testing authentication in NestJS. We'll cover strategies, tools, and best practices to ensure robust authentication mechanisms. Topics include unit testing and mocking dependencies. By the end, you'll gain a comprehensive understanding of how to effectively test authentication in your NestJS applications.
Below, you will find the default content of the file, which serves as a starting point for testing. If you are already familiar with tests, you'll quickly grasp its structure and purpose. However, if you're new to testing, don't worry—I'll provide detailed explanations with comments for each part to help you understand it better.
Now we will test the resolver/controller (are the same) :
▪️ the first case is the signup
1️⃣ : On the providers, you need to add all the services you use. In my case, it would be like this
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
AuthResolver,
AuthService,
PasswordService,
JwtService,
PrismaService,
ConfigService,
],
}).compile();
resolver = module.get<AuthResolver>(AuthResolver);
authService = module.get<AuthService>(AuthService);
});
⚠️: I added the authService because I will use it later to spy actions performed by my resolver.
2️⃣ : add the test case :
3️⃣ : mock the input data and the tokens
const data: SignupInput = {
email: 'test@example.com',
roleId: 'admin',
password: 'password',
username: 'testName',
};
const tokens = {
accessToken: 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJmb29',
refreshToken: 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJmb29',
};
4️⃣ : we need to spy the createUser method that exist on our authService by using this line :
//spyOn: allows you to create a spy on a particular method of an object or class
const createUserSpy = jest.spyOn(authService, 'createUser');
// mock the resolved value of the createUser method
createUserSpy.mockResolvedValue(tokens);
5️⃣ : mock the cookies
const cookieMock = jest.fn();
response.cookie = cookieMock;
6️⃣ : and now it's time to calling the signup method of the resolver object, which corresponds to the signup resolver function
// It will simulate the signup process using our mock data
const result = await resolver.signup(data, response);
7️⃣ : and the last steo is to set the expectations :
expect(createUserSpy).toHaveBeenCalledWith(data, response);
expect(cookieMock).toHaveBeenCalledWith(
'refreshToken',
tokens.refreshToken
);
expect(result).toEqual(tokens);
The final result : 👇
With the same way we can test the others :
▪️ Login:
▪️ RefreshToken:
▪️ decodeUser:
Finally,
I don't test all cases to keep the blog lightweight. Feel free to message me for more details or if you have any questions. I hope you find it enjoyable. See you in another blog 👋.
Top comments (0)