Nestjs 测试 - 服务方法在不应该的时候返回数据



我正在编写一个单元测试,模拟在数据库中创建新用户。在user.service.add方法中,我执行findOne调用来检查数据库中是否存在用户。然而,在开发过程中,这是正确的,在测试中,findOne会在不应该返回数据的时候返回数据。

至少我认为不应该。为什么要返回数据?

我的测试

const testUserUsername1 = faker.internet.userName();
const testUserEmail1 = faker.internet.email();
const testUserPassword1 = faker.internet.password();
const testUserName1 = `${faker.name.firstName()} ${faker.name.lastName()}`;
const testUserName2 = `${faker.name.firstName()} ${faker.name.lastName()}`;
// user test object
const testUser = new User(
testUserName1,
testUserEmail1,
testUserPassword1,
testUserUsername1,
);
describe('UserService', () => {
let userService: UserService;
let postService: PostService;
let likeService: LikeService;
let userRepository: Repository<User>;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
UserService,
{
provide: getRepositoryToken(User),
useClass: Repository,
},
{
provide: getRepositoryToken(User),
// mocks of all the methods from the User Service
useValue: {
save: jest.fn(),
create: jest.fn().mockReturnValue(testUser),
find: jest.fn().mockResolvedValue(testUsers),
findOne: jest.fn().mockResolvedValue(testUser),
update: jest.fn().mockResolvedValue(testUser),
delete: jest.fn().mockResolvedValue(true),
},
},
PostService,
{
provide: PostService,
useClass: Repository,
},
LikeService,
{
provide: LikeService,
useClass: Repository,
},
],
}).compile();
userRepository = module.get<Repository<User>>(getRepositoryToken(User));
userService = module.get<UserService>(UserService);
postService = module.get<PostService>(PostService);
likeService = module.get<LikeService>(LikeService);
});
it('should be able to create a user', async () => {
const tempUser = {
name: testUserName1,
email: testUserEmail1,
username: testUserUsername1,
password: testUserPassword1,
}
userRepository.findOne = jest.fn(() => tempUser.username);
await userService.add(tempUser)
expect(tempUser).toEqual(testUser);
});
afterEach(() => {
jest.resetAllMocks();
});
});

user.service.add

async add(userDto: Partial<UserCreateDTO>): Promise<UserDTO> {
// get data from args
const { name, password, username, email } = userDto;
// check if the user exists in the db
const userInDb = await this.userRepository.findOne({
where: { username },
});
console.log('username: ', username)
console.log('userInDb: ', userInDb)
if (userInDb) {
throw new HttpException('User already exists', HttpStatus.BAD_REQUEST);
}
// create new user 
const user: User = await this.userRepository.create({
name,
password,
username,
email,
});
// save changes to database
await this.userRepository.save(user);
// return user object
return toUserDto(user);
}

user.service.add内部的console.log输出

console.log src/user/user.service.ts:49
username: Mayra_Rolfson53
console.log src/user/user.service.ts:50
userInDb: User {
name: 'Albert Kuvalis',
email: 'Martin_Jacobson@gmail.com',
username: 'SQT_L6iGKzPVFPI',
password: 'Mayra_Rolfson53'
}

抛出错误

User already exists
50 |     console.log('userInDb', userInDb)
51 |     if (userInDb) {
> 52 |       throw new HttpException('User already exists', HttpStatus.BAD_REQUEST);
|             ^
53 |     }

我认为解决方案是当在我的findOne方法中发现用户NOT时添加一个返回类型

之前

async findOne(uid: string): Promise<User> {
return await this.userRepository.findOne({
relations: ['posts', 'comments'],
where: { uid },
});
}

async findOne(uid: string): Promise<User | undefined> {
return await this.userRepository.findOne({
relations: ['posts', 'comments'],
where: { uid },
});
}

现在,在我的测试中,我希望在我的findOne模拟中返回undefined而不是testUser

it('should be able to create a user', async () => {
const tempUser = {
name: testUserName1,
email: testUserEmail1,
username: testUserUsername1,
password: testUserPassword1,
}
userRepository.findOne = jest.fn(() => undefined);
await userService.add(tempUser)
expect(tempUser).toEqual(testUser);
});

我的测试现在通过了。我不知道这是否是TypeScript或Nest.js测试的最佳实践。如果有人有更好的建议,请随时发布!

感谢@amakhrov在评论中的提示!

最新更新