NestJS测试失败:无法设置未定义的属性"电子邮件"



我在 NestJS 应用程序的测试文件中看到了一个奇怪的错误。我似乎无法弄清楚出了什么问题:我有一个TypeORM存储库的测试文件:

describe('UserRepository', () => {
let userRepository;
beforeEach(async () => {
const module = await Test.createTestingModule({
providers: [
UserRepository,
],
}).compile();

userRepository = await module.get<UserRepository>(UserRepository);
});
describe('signUp', () => {
let save;
beforeEach(() => {
save = jest.fn();
userRepository.create = jest.fn().mockReturnValue({ save });
});
it('successfully signs up the user', async () => {
save.mockResolvedValue(undefined);
expect(
userRepository.createUser(mockCredentialsDto),
).resolves.not.toThrow();
});
});
});

还有一个存储库:

@EntityRepository(User)
export class UserRepository extends Repository<User> {
async createUser(signUpDto: SignUpDto) {
const { password, email } = signUpDto;
const salt = await bcrypt.genSalt();
const encodedPassword = await bcrypt.hash(password, salt);
const user: any = this.create();
user.email = email;
user.password = encodedPassword;
user.salt = salt;
await user.save();
return user;
}
}

但是,this.create()方法似乎不起作用。它似乎返回undefined,最终我的测试出现错误(即使测试都通过了:

收到的承诺被拒绝而不是已解决 拒绝值: [类型错误:无法设置未定义的属性'电子邮件']

谁能帮忙?我似乎想不通,为什么user是不确定的。

缺少的是测试的返回语句(!(:

以下是 Jest 文档的摘录:

"请务必返回断言 - 如果你省略了这个 return 语句,你的测试将在解析从 fetchData 返回的承诺之前完成,然后(( 有机会执行回调。">

这是正确的测试:

it('throws a conflict exception as username already exists', () => {
save.mockRejectedValue({ code: '23505' });
return expect(
userRepository
.createUser(mockCredentialsDto),
).rejects.toThrow(ConflictException);
});

最新更新