E2E Testing
The end to end testing is a great way to verify how the application works from beginning to end. For example, when the application grows, it's difficult to manually test every API endpoint. The e2e tests help us to make sure that everything's working correctly and fits our requirements.
The steps to perform e2e tests are exactly the same as in the case of unit testing.
We're using Jest library as a test runner and the Test static class to create a testing module.
Moreover, to simulate the HTTP requests, we've installed the supertest library.
Let's create an e2e directory and test the CatsModule.
import * as express from 'express';
import * as request from 'supertest';
import { Test } from '@nestjs/testing';
import { CatsModule } from '../../src/cats/cats.module';
import { CatsService } from '../../src/cats/cats.service';
describe('Cats', () => {
const server = express();
const catsService = { findAll: () => ['test'] };
beforeAll(async () => {
const module = await Test.createTestingModule({
imports: [CatsModule],
})
.overrideComponent(CatsService).useValue(catsService)
.compile();
const app = module.createNestApplication(server);
await app.init();
});
it(`/GET cats`, () => {
return request(server)
.get('/cats')
.expect(200)
.expect({
data: catsService.findAll(),
});
});
});
Hint Keep your e2e test files inside thee2edirectory. The testing files should have a.e2e-specor.e2e-testsuffix.
Here's a cats.e2e-spec.ts test file. It contains a single HTTP request test, where we're checking whether the response looks like expected.
Notice that TestingModule instance provides an overrideComponent() method thus we can override the component which is the part of the imported module.
Also, we can successively override the guards and interceptors using overrideGuard() and overrideInterceptor().
The compiled module has several methods well described in the following table:
createNestInstance()
|
Takes an optional argument - the express instance, and returns the INestApplication.
It's necessary to manually initialize the application using init() method.
|
createNestMicroservice()
|
Takes MicroserviceConfiguration as an argument, and returns the INestMicroservice.
|
get()
|
Makes possible to retrieve the instance of the component or controller available inside the processed module. |
select()
|
Allows you to navigate through the module tree, for example, to pull out a specific instance from the selected module. |