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()
})
The other option is to have a special database that is seeded with the correct data and is reset when the tests are run each time. Speed is a big problem when running E2E tests, as it can take 4–8 hours to test a large suite of tests.
End-to-end testing is a methodology that assesses the working order of a complex product in a start-to-finish process. End-to-end testing verifies that all components of a system are able to run and perform optimally under real-world scenarios.
You can add them before you initialize the testing module:
beforeEach(async done => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule]
}).compile()
app = moduleFixture.createNestApplication()
// Add global pipe here
app.useGlobalPipes(new ValidationPipe({ transform: true, whitelist: true, forbidNonWhitelisted: true }))
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.
Another approach is to declare the global pipes in the module using APP_PIPE
.
@Module({
providers: [
{
provide: APP_PIPE,
useClass: ValidationPipe,
},
],
})
export class AppModule {}
Then it will be available in your e2e tests.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With