Reputation: 1499
I'm adding tests on a project and improving coverage. I would like to know how can I test a module definition (mymodule.module.ts file) in NestJs. In particular, I'm testing a main module that imports other modules, one of them inits a db connection, this means that I need to mock the service on the other module, to avoid a real db connection. At this moment I have something like this:
beforeEach(async () => {
const instance: express.Application = express();
module = await NestFactory.create(MyModule, instance);
});
describe('module bootstrap', () => {
it('should initialize entities successfully', async () => {
controller = module.get(MyController);
...
expect(controller instanceof MyController).toBeTruthy();
});
});
This works, but I'm sure this can get improvements :)
The ideal thing would be something like overrideComponent method provided by Test.createTestingModule.
P.S: I'm using 4.5.2 version
Upvotes: 8
Views: 23169
Reputation: 53
You can now test your module (at least for code coverage) by building it that way:
describe('MyController', () => {
let myController: MyController;
beforeEach(async () => {
const module = await Test.createTestingModule({
imports: [MyModule],
}).compile();
myController = module.get<MyController>(MyController);
});
it('should the correct value', () => {
expect(myController.<...>).toEqual(<...>);
});
});
Upvotes: 5
Reputation: 685
Improved my tests based on @laurent-thiebault answer:
import { Test } from '@nestjs/testing';
import { ThingsModule } from './things.module';
import { ThingsResolver } from './things.resolver';
import { ThingsService } from './things.service';
describe('ThingsModule', () => {
it('should compile the module', async () => {
const module = await Test.createTestingModule({
imports: [ThingsModule],
}).compile();
expect(module).toBeDefined();
expect(module.get(ThingsResolver)).toBeInstanceOf(ThingsResolver);
expect(module.get(ThingsService)).toBeInstanceOf(ThingsService);
});
});
Upvotes: 11
Reputation: 187
We usually didn't test .module.ts
files directly.
we do this in e2e
testing.
but I wonder why one should test the the module !
and you are trying to test if the module can initialize it's components , it should.
but i recommend you do this in e2e
testing.
in my opinion, in unit testing you should focus on testing the services or other components behaviors not the modules.
Upvotes: 4