【发布时间】:2021-06-25 14:41:24
【问题描述】:
我有一个带有 CSRF 保护的 NestJS 后端和一个用于获取 CSRF 令牌的端点。使用 jest 和 supertest 测试此端点时,我收到了 TypeError: req.csrfToken is not a function。
我的代码是这样的:
// main.ts
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.use(cookieParser());
app.use(csurf({ cookie: true }));
await app.listen(process.env.BACKEND_SERVER_PORT);
}
// authController.ts
import { Controller, Req, Get } from "@nestjs/common";
import { Request } from "express";
import * as AuthDto from "./modules/auth/dto/auth.dto";
@Controller("auth")
export class AppController {
constructor() {}
@Get("csrf")
async getCsrfToken(@Req() req: Request): Promise<AuthDto.CsrfOutput> {
return { csrfToken: req.csrfToken() }; // <-- ERROR HAPPENS HERE
}
}
// app.controller.spec.ts
import { Test, TestingModule } from "@nestjs/testing";
import { INestApplication } from "@nestjs/common";
import request from "supertest";
import AppModule from "../src/app.module";
describe("AppController (e2e)", () => {
let app: INestApplication;
let server: any;
beforeAll(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleFixture.createNestApplication();
await app.init();
server = app.getHttpServer();
});
it("/csrf (GET)", () => {
return request(server).get("/auth/csrf").expect(200).expect("hello");
// I'll add more validations here once I get past this error
});
});
我相信这可能与测试本身有关,因为这个端点在被外部客户端(我们的前端应用程序或 Postman)调用时工作正常。它只是不适用于超测。
有人知道为什么吗?谢谢。
【问题讨论】:
标签: node.js express jestjs nestjs csrf