2
votes

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

2

2 Answers

1
votes

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.

1
votes

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(<...>);
   });
});