Nest: Mocking data to test 07-sequelize sample

Created on 13 Apr 2020  路  2Comments  路  Source: nestjs/nest

I have a working application based on the 07-sequelize sample, but am confused with the doco that outlines how to mock a model when testing . It talks about a mockModel object but does not provide a more detailed example.

Below is what I have got working. I expect the goal here is to mock the UsersService (repository) - to provide mock data instead of real data - to test controller and service functions without hitting the database.

The below does that, but I have an issue with it - usersController.findOne returns a Promise<User> but when mocked below this type is not constrained. I thought I might instantiate a User model object to provide a mock response (e.g. return new User({ name: "Bob" })), but in doing so I get error Model not initialized: User cannot be instantiated. "User" needs to be added to a Sequelize instance.

This question clearly falls into "support" but I wonder whether we could expand the docs a bit to explain what I am (inevitably) doing wrong here.

import { Test, TestingModule } from '@nestjs/testing';
import { UsersController } from './users.controller';
import { UsersService } from './users.service';
import { getModelToken } from '@nestjs/sequelize';
import { User } from './user.model';

const mockUserService = {
  findOne(id: string) {
    return "some value";
  }
};

describe('Users Controller', () => {
  let usersController: UsersController;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        UsersService,
        {
          provide: getModelToken(User),
          useValue: mockUserService,
        }
      ],
      controllers: [UsersController],
    }).compile();

    usersController = module.get<UsersController>(UsersController);
  });

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

  describe('findOne', () => {
    it('should return User', async () => {
      const result = "some value";
      expect(await usersController.findOne('1')).toBe(result);
    });
  });

});

needs triage question 馃檶

Most helpful comment

This part of the documentation really needs some improvements.

All 2 comments

Please, use our Discord channel (support) for such questions. We are using GitHub to track bugs, feature requests, and potential improvements.

This part of the documentation really needs some improvements.

Was this page helpful?
0 / 5 - 0 ratings