Remaining service tests
We already have a structure to easily implement the remaining tests.
Inside the describe() for the findOne() method, we may then have another describe() below the previous one for when a user is not found. What we'll do:
Have an
exceptionrepresenting this situationMake the
repositorymethod return a rejected promise with thisexceptionCheck if the
exceptionwas propagated
describe('otherwise', () => {
it('should propagate the exception', async () => {
const id = 1;
const exception = new NotFoundException('User not found');
repository.findOneByOrFail.mockRejectedValueOnce(exception);
let error: Error;
try {
await service.findOne(id);
} catch (err) {
error = err;
}
expect(error).toBe(exception);
});
});Alright, now for findAll(). This one will be quite simple, we:
Create an array with
expectedUsersMake the
find()method of therepositoryreturn themCheck if the obtained
usersmatch theexpectedUsers
For create(), let's:
Have a fake
createUserDtoand anexpectedUserwith the contents of this DTOMake the
create()andsave()methods of therepositoryreturn them, respectivelyCheck if the result matches the expectation
It should also propagate exceptions, so let's test this too.
For update(), we:
Have an
existingUser, a fakeupdateUserDtoand anexpectedUser, which receives the contents of theexistingUserand then, of theupdateUserDtoover themHave
preload()andsave()return theexpectedUsedPerform the assertion, as usual
And also check in the case of an exception. Remember that, in this case, it's the service itself that throws it and not the repository. There is no need to mock the return of the repository methods here because they don't return anything by default. So, when preload() returns undefined, the exception will be thrown, similarly to when the user is not found.
In the case of remove(), we have an interesting difference. Here, we call the findOne() method of the service itself. It would be interesting to mock it here, as we don't want to have its actual functionality, as it is not the focus of this test. But how could we achieve this, as it is a method from the actual service and not from a mock? This can be done with the spyOn() function from Jest. It allows for applying a mocked implementation to a "normal" method through the following form:
We can do the same in the case of an exception.
And we're done! Let's then proceed to the tests for the UsersController. They will be quite simple.
Last updated