Open nyeong opened 1 year ago
Let's use UserService
as an example.
UserService
dependence on Repository<User>
and JwtService
. Mockup those.
const mockRepository = {
findOneBy: jest.fn(),
save: jest.fn(),
// ...
}
Inject dependencies using mockups.
describe('UserService', () => {
let service: UserService;
let repository: Repository<User>;
beforeEach(async () => {
const moduleRef: TestingModule = await Test.createTestingModule({
providers: [
UserService,
{ // use `mockRepository` value instead of `Repository<User>`
provide: getRepositoryToken(User),
useValue: mockRepository
}
],
}).compile();
service = moduleRef.get(UserService);
repository = moduleRef.get(Repository<User>)
});
});
And test whether the function is called using jest.spyOn
function.
describe('create', () => {
it('should create a user with proper input', async () => {
const spySave = jest.spyOn(repository, 'save')
const createDto = new CreateDto({
email: "email@example.com",
username: "example",
password: "rootme"
})
service.create(createDto)
expect(spySave).toBeCalled()
})
it.todo('should throw an error if the given email already taken');
});
See also NestJS.
Unit Tests
E2E Tests