提问者:小点点

异常csrfToken在被超级测试调用时不是函数


我有一个带有CSRF保护的NestJS后端和一个获取CSRF令牌的endpoint。在使用jest和supertest测试此endpoint时,我得到typeerror:req.csrftoken不是函数

我的代码是这样的:

// 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
  });
});

我相信这可能与测试本身有关,因为当外部客户端(我们的前端应用程序或邮递员)调用该endpoint时,该endpoint可以正常工作。它对超级测试不起作用。

有人知道为什么吗?多谢了。


共1个答案

匿名用户

您只在main.ts中注册csurf,但是您的测试直接使用AppModule。AppModule不会自己注册csurf。因此,当测试创建您的AppModule时,它没有必要的中间件。