Search code examples
node.jsmongoosenestjs

Mocking a MongooseModule import in Nestjs tests


I'm experimenting with NestJs, following a tutorial. I've decided I want to write some tests on the code I've written.

I'm writing tests for the ProductController and the test file for the controller mocks the ProductModule to which the controller belongs. My ProductModule imports MongooseModule and presumably I need to mock that import in the TestingModule of the controller test file.

How can I go about mocking that import?

ProductModule;

import { Module } from '@nestjs/common';
import { ProductController } from './product.controller';
import { ProductService } from './product.service';
import { MongooseModule } from '@nestjs/mongoose';
import { ProductSchema } from './schemas/product.schema';

@Module({
  imports: [
    MongooseModule.forFeature([{ name: 'Product', schema: ProductSchema }]),
  ],
  providers: [ProductService],
  controllers: [ProductController],
})
export class ProductModule {}

ProductController test file;

import { Test, TestingModule } from '@nestjs/testing';
import { ProductController } from './product.controller';
import { ProductService } from './product.service';

describe('ProductController', () => {
  let controller: ProductController;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [ProductService],
      controllers: [ProductController],
    }).compile();

    controller = module.get<ProductController>(ProductController);
  });

  it('should be defined', () => {
    expect(controller).toBeDefined();
  });
});

Solution

  • For the ProductController test I'd use a custom provider like

    {
      provide: ProductService,
      useValue: {
        method1: jest.fn(),
        methodN: jest.fn()
      }
    }
    

    For your ProductService test I'd mock the @InjectModel('Product') by using getModelToken() and a custom provider like

    {
      provide: getModelToken('Product'),
      useValue: {
        productModelMethod1: jest.fn(),
      }
    }
    

    You can see a repo here with a bunch of test examples