In the previous posts, I have write a lot of testing codes to verify if our application is working as expected.
Nestjs provides integration with with Jest and Supertest out-of-the-box, and testing harness for unit testing and end-to-end (e2e) test.
Like the Angular ‘s TestBed
, Nestjs provide a similar Test
facilities to assemble the Nestjs components for your testing codes.
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
...
],
}).compile();
service = module.get<UserService>(UserService);
});
Similar to the attributes in the @Module
decorator, creatTestingModule
defines the components that will be used in the tests.
We have demonstrated the methods to test a service in Nestjs applications, eg. in the post.service.spec.ts
.
To isolate the dependencies in a service, there are several approaches.
providers
.providers: [ provide: UserService, useValue: { send: jest.fn() } ],
new
to instantize your service in the setup
hooks.You can also import a module in Test.createTestingModule
.
Test.createTestingModule({
imports: []
})
To replace some service in the imported modules, you can override
it.
Test.createTestingModule({
imports: []
})
.override(...)
#programming #jest #tdd #nestjs #javascript