我在模拟 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;
...
}
}
这就是我在单元测试中尝试的内容。
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);
});
我遇到了这种错误。
Cannot spy the getRequest property because it is not a function; undefined given instead
我希望您建议任何其他方式来模拟上下文。谢谢。
请检查这个库https://www.npmjs.com/package/@golevelup/ts-jest https://www.npmjs.com/package/@golevelup/ts-jest
然后您可以如下模拟 ExecutionContext。
import { createMock } from '@golevelup/ts-jest';
import { ExecutionContext } from '@nestjs/common';
describe('Mocked Execution Context', () => {
it('should have a fully mocked Execution Context', () => {
const mockExecutionContext = createMock<ExecutionContext>();
expect(mockExecutionContext.switchToHttp()).toBeDefined();
...
});
});
希望能帮助到你
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)