How do you apply global pipes when using Test.createTestingModule
?
Normally, global pipes are added when the application is mounted in main.ts
.
beforeEach(async done => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule]
}).compile()
app = moduleFixture.createNestApplication()
await app.init()
done()
})
Here's what I do to ensure that the global pipes in my main.ts
file are always in sync with my testing setup...
Start by creating a new file called main.config.ts
, this should contain your global pipes, filters, etc:
import { INestApplication, ValidationPipe } from "@nestjs/common";
export function mainConfig(app: INestApplication) {
app.enableCors();
app.useGlobalPipes(new ValidationPipe());
}
Next, use the newly created mainConfig
function in both the main.ts
and app.e2e-spec.ts
(or wherever you setup your tests):
main.ts
import { NestFactory } from "@nestjs/core";
import { mainConfig } from "main.config";
import { AppModule } from "./app.module";
async function bootstrap() {
const app = await NestFactory.create(AppModule);
// use here
mainConfig(app);
await app.listen(3000);
}
bootstrap();
app.e2e-spec.ts
import { INestApplication } from "@nestjs/common";
import { TestingModule, Test } from "@nestjs/testing";
import { AppModule } from "app.module";
import { mainConfig } from "main.config";
let app: INestApplication;
beforeEach(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleFixture.createNestApplication();
// use here
mainConfig(app);
await app.init();
});
Now if you need to add a new pipe, you'll only have to make the change in one spot (main.config.ts
) to see it reflected in both the app and the tests.