我在 Guard 中间件中模拟 ExecutionContext 时遇到了麻烦。
这是我的 RoleGuard 扩展 JwtGuard
@Injectable()
export class RoleGuard extends JwtAuthGuard {
...
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest();
const params = request.params;
...
}
}
Run Code Online (Sandbox Code Playgroud)
这就是我在单元测试中所尝试的。
let context: ExecutionContext = jest.genMockFromModule('@nestjs/common');
context.switchToHttp = jest.fn().mockResolvedValue({
getRequest: () => ({
originalUrl: '/',
method: 'GET',
params: undefined,
query: undefined,
body: undefined,
}),
getResponse: () => ({
statusCode: 200,
}),
});
jest.spyOn(context.switchToHttp(), 'getRequest').mockImplementation(() => {
return Promise.resolve(null);
});
Run Code Online (Sandbox Code Playgroud)
我收到了这种错误。
Cannot spy the getRequest property because it …Run Code Online (Sandbox Code Playgroud) export class Contact extends BaseEntity {
...
@ManyToOne(() => User, { nullable: false })
@JoinColumn({ name: 'user_id' })
user: User;
...
}
const repo = new Repository<User> ();
const response = await repo.findAll();
console.log(response);
console.log:
[
Contact {
id: 1,
...
},
Contact {
id: 2,
...
}
]
Run Code Online (Sandbox Code Playgroud)
我正在尝试获取包含在 my 中的所有列Contact,但我只能获取与其他实体没有任何关系的列。它不包括 user_id 列。例如为什么不能获取外键?
我想创建自定义装饰器并applyDecorators导入自@nestjs/common
...
applyDecorators(
@Field(),
@MinLength(2)
)
...
Run Code Online (Sandbox Code Playgroud)
但我遇到了 Typescript lint 错误。如何创建一个包含多个装饰器的自定义装饰器?
https://docs.nestjs.com/custom-decorators
"class-validator": "^0.11.0"
"@nestjs/common": "^7.0.9"
Run Code Online (Sandbox Code Playgroud)