unit-testing - 期望(jest.fn()).toHaveBeenCalledWith(...期望)
问题描述
我正在尝试为用 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.validateUser(payload);
return await this.authService.createToken(user);
}
上述代码的单元测试是在 JEST 框架中编写的。
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)
解决方案
您的controller.login
方法是异步的,因此您不应await controller.login(registerPayload)
直接调用它。我有一种感觉,您在开玩笑并没有等待nextTick
处理,而是在不让控制器方法运行其段的情况下继续前进
推荐阅读
- javascript - 尝试在 node.js 中发出 PUT 请求
- typescript - 混合联合类型、泛型和条件类型会导致意外的“类型不可分配给类型”错误
- .htaccess - httaccess 301 重定向没有 URL 变量
- r - 突出显示绘图上的多个点:ggplot
- php - 获取下拉隐藏 id 并使用 $_POST 获取它
- http - 当预期 405 时,服务器以状态代码 200 响应
- wordpress - WP_Query - 显示一个随机帖子,然后显示另外三个随机帖子,而不重复第一个
- c# - 定义路由的 Web API 控制器
- jupyter-notebook - 如何禁用 jupyterlab markdown 单元格上的滚动条?
- c# - 如何在检查器中创建游戏对象的动态“数组”