【发布时间】:2020-05-03 03:53:51
【问题描述】:
我在 NestJS 中配置了一个控制器,我想检查是否设置了适当的保护 - 有没有人有一个如何做到的例子?
这个(删节的)示例作为应用程序可以正常工作,所以我只是在测试指导之后。
您会在用户测试中注意到我调用Reflect.getMetadata 的测试。我正在追求这样的东西 - 当我在 __guards__ 元数据上检查它时,这是一个函数,我正在努力模拟它,所以我可以检查它是否在设置时与 AuthGuard('jwt') 一起应用。
用户.controller.ts
@Controller('/api/user')
export class UserController {
@UseGuards(AuthGuard('jwt'))
@Get()
user(@Request() req) {
return req.user;
}
}
User.controller.spec.ts
describe('User Controller', () => {
// beforeEach setup as per the cli generator
describe('#user', () => {
beforeEach(() => {
// This is how I'm checking the @Get() decorator is applied correctly - I'm after something for __guards__
expect(Reflect.getMetadata('path', controller.user)).toBe('/');
expect(Reflect.getMetadata('method', controller.user)).toBe(RequestMethod.GET);
});
it('should return the user', () => {
const req = {
user: 'userObj',
};
expect(controller.user(req)).toBe(req.user);
});
});
});
【问题讨论】:
-
我曾经使用 e2e 进行此测试,但在我看来,它们绝对是完全有效的回归测试。
-
@RuslanGonzalez 是的,e2e 测试很重要。我认为 e2e 测试检查它们是否应用了正确的功能,而单元测试检查它们是否被应用——两者对于它们协同工作都很重要且至关重要。不过,单元测试往往更快
标签: node.js typescript jestjs nestjs