Unit testing expect(jest.fn())。与(…expected)一起调用
我正在尝试为用NEST.JS编写的控制器编写单元测试 以下是单元测试失败的登录方法Unit testing expect(jest.fn())。与(…expected)一起调用,unit-testing,jestjs,nestjs,Unit Testing,Jestjs,Nestjs,我正在尝试为用NEST.JS编写的控制器编写单元测试 以下是单元测试失败的登录方法 @Post('login') async login(@Body() payload: LoginPayload): Promise<any> { this.logger.info("Calling Loging"); this.logger.debug("Calling Loging"); const user = await this.authService.validat
@Post('login')
async login(@Body() payload: LoginPayload): Promise<any> {
this.logger.info("Calling Loging");
this.logger.debug("Calling Loging");
const user = await this.authService.validateUser(payload);
return await this.authService.createToken(user);
}
您的
controller.login
方法是异步的,因此您应该wait controller.login(registerPayload)
而不是直接调用它。我有一种感觉,您不是在等待nextTick
处理,而是在不让controller方法运行其段的情况下继续运行您的控制器。login
方法是异步的,因此您应该等待controller.login(registerPayload)
而不是直接调用它。我有一种感觉,您不是在等待nextTick
处理,而是在不让控制器方法运行其段的情况下继续进行操作那么,测试它的正确方法是什么呢?“所以应该是wait controller.login(registerPayload)
”-引用我的评论。必须等待异步方法。就这么简单。好吧,我就是这样做的,它不起作用,非常奇怪。那么,测试它的正确方法是什么呢?“所以应该是wait controller.login(registerPayload)
”-引用我的评论。必须等待异步方法。就这么简单。嗯,我就是这样做的,没用,很奇怪。
beforeEach(async () => {
// createInputDetails() Functions initializes the LoginPayload, RegisterPayload and User Object
createInputDetails();
module = await Test.createTestingModule({
controllers: [AuthController],
providers: [
{
provide: AuthService,
useFactory: () => ({
createToken: jest.fn(() => true),
validateUser: jest.fn(() => true),
}),
},
{
provide: UserService,
useFactory: () => ({
get: jest.fn(() => true),
getByEmail: jest.fn(() => true),
getByEmailAndPass: jest.fn(() => true),
create: jest.fn(() => true),
}),
},
],
}).compile();
controller = module.get<AuthController>(AuthController);
authService = module.get<AuthService>(AuthService);
userService = module.get<UserService>(UserService);
});
describe('login', () => {
it('should validate user', async () => {
controller.login(loginPayload);
expect(authService.validateUser).toHaveBeenCalledWith(loginPayload);
expect(authService.createToken).toHaveBeenCalledWith(user);
})
})
expect(jest.fn()).toHaveBeenCalledWith(...expected)
Expected: {"email": "abc@xyz.com", "firstName": "abc", "lastName": "pqr", "password": "Test@1234", "profile": {"age": 32, "nickname": "abc"}, "userId": 14}
Number of calls: 0
96 | controller.register(registerPayload);
97 | // expect(userService.create).toHaveBeenCalledWith(registerPayload);
> 98 | expect(authService.createToken).toHaveBeenCalledWith(user);
| ^
99 | })
100 | })
101 |
at Object.it (modules/auth/auth.controller.spec.ts:98:39)