В проекте используется гнездо js, а тестирование интегрировано с jest js.
Я пытаюсь протестировать функцию «getUserByID», которая находится в моем «user.repository. js»
import { Test } from '@nestjs/testing';
import { UserService } from './user.service';
import { UserRepository } from './user.repository';
import { UserModifyDto } from './dto/user-modify.dto';
import { ConflictException, InternalServerErrorException, NotFoundException, Logger, BadRequestException } from "@nestjs/common";
const mockUser = { id: 1, email: "email@email.com", password: "pass", salt: "XCVBxcf", isAdmin: false, isActive: true, activated: true };
const mockUserRepository = () => ({
modifyUser: jest.fn(),
remove: jest.fn(),
getUserById: jest.fn(),
});
describe('User service', () => {
let userService;
let userRepository;
beforeEach(async () => {
const module = await Test.createTestingModule({
providers: [
UserService,
{ provide: UserRepository, useFactory: mockUserRepository }
],
}).compile();
userService = await module.get<UserService>(UserService);
userRepository = await module.get<UserRepository>(UserRepository);
});
describe('modifyUser', () => {
it('modify email', async () => {
userRepository.modifyUser.mockResolvedValue({ email: "newEmail@email.com" });
expect(userRepository.modifyUser).not.toHaveBeenCalled();
const myModifyUser: UserModifyDto = { email: "newEmail@email.com", password: "pass", oldPassword: "pass", isActive: true, activated: true };
const result = await userService.modifyUser(mockUser, myModifyUser);
expect(userRepository.modifyUser).toHaveBeenCalled();
expect(result.email).toEqual(myModifyUser.email);
});
it('modify password', async () => {
userRepository.modifyUser.mockResolvedValue({ password: "newpass" });
expect(userRepository.modifyUser).not.toHaveBeenCalled();
const myModifyUser: UserModifyDto = { email: "email@email.com", password: "newpass", oldPassword: "pass", isActive: true, activated: true };
const result = await userService.modifyUser(mockUser, myModifyUser);
expect(userRepository.modifyUser).toHaveBeenCalled();
expect(result.password).toEqual(myModifyUser.password);
});
it('modify active', async () => {
userRepository.modifyUser.mockResolvedValue({ isActive: false });
expect(userRepository.modifyUser).not.toHaveBeenCalled();
const myModifyUser: UserModifyDto = { email: "email@email.com", password: "pass", oldPassword: "pass", isActive: false, activated: true };
const result = await userService.modifyUser(mockUser, myModifyUser);
expect(userRepository.modifyUser).toHaveBeenCalled();
expect(result.isActive).toEqual(myModifyUser.isActive);
});
it('modify activated', async () => {
userRepository.modifyUser.mockResolvedValue({ activated: false });
expect(userRepository.modifyUser).not.toHaveBeenCalled();
const myModifyUser: UserModifyDto = { email: "email@email.com", password: "pass", oldPassword: "pass", isActive: true, activated: false };
const result = await userService.modifyUser(mockUser, myModifyUser);
expect(userRepository.modifyUser).toHaveBeenCalled();
expect(result.activated).toEqual(myModifyUser.activated);
});
it('modify but wrong old password', async () => {
userRepository.modifyUser.mockImplementation(() => {
throw new BadRequestException;
});
});
it('modify but save impossible', async () => {
userRepository.modifyUser.mockImplementation(() => {
throw new InternalServerErrorException;
});
});
});
describe('getUserById', () => {
it ('get a user', async () => {
//userRepository.findOne.mockResolvedValue(mockUser.id);
userRepository.getUserById.mockResolvedValue(mockUser.id);
const result = await userRepository.getUserById(mockUser.id);
expect(result.id).toEqual(mockUser.id);
})
})
describe('Delete User', () => {
it('Delete user without error', async () => {
userRepository.remove.mockResolvedValue({ affected: 1});
expect(userRepository.remove).not.toHaveBeenCalled();
await userService.deleteUser(mockUser);
expect(userRepository.remove).toHaveBeenCalledWith({mockUser})
})
})
});
настройка моего тестового файла:
const mockUser = { id: 1, email: "email@email.com", password: "pass", salt: "XCVBxcf", isAdmin: false, isActive: true, activated: true };
const mockUserRepository = () => ({
modifyUser: jest.fn(),
remove: jest.fn(),
getUserById: jest.fn(),
});
describe('User service', () => {
let userService;
let userRepository;
beforeEach(async () => {
const module = await Test.createTestingModule({
providers: [
UserService,
{ provide: UserRepository, useFactory: mockUserRepository }
],
}).compile();
userService = await module.get<UserService>(UserService);
userRepository = await module.get<UserRepository>(UserRepository);
});
и это мой тест:
describe('getUserById', () => {
it ('get a user', async () => {
const mockUserForGet = {id : 1, email: "mock@email.com"};
userRepository.getUserById.mockResolvedValue(mockUserForGet.id);
const result = await userRepository.getUserById(mockUserForGet.id);
expect(result.id).toEqual(mockUserForGet.id);
})
})
Итак, моя проблема заключается в следующем, когда я запускаю тест , я получил следующий результат:
ожидать (получено) .toEqual (ожидалось)
Ожидается: 1 Получено: undefined
Я не не знаю почему. Функция not throw и функция mock - это начало моего тестового файла.
Спасибо за вашу помощь!