Home > Mobile >  Can't create mock constructor for user model
Can't create mock constructor for user model

Time:04-08

When I'm trying to mock my user model to test my service, the nest console throws this TypeError, but I don't know how 'emulate' the constructor of user model

user.service.spec.ts

import { Test, TestingModule } from '@nestjs/testing';
import { getModelToken } from '@nestjs/mongoose';
import { UserService } from './user.service';
import { User } from './interfaces/user.interface';

const mockUsersModel = {
  save: jest.fn().mockImplementation((user) => Promise.resolve({id: Date.now(), ...user}))
};

describe('UserService', () => {
  let service: UserService;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [UserService,
      {
        provide: getModelToken('User'),
        useValue: mockUsersModel
      }],
    }).compile();

    service = module.get<UserService>(UserService);
  });

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

  it('should create a new user record and return it', async() => {
    expect(await service.createUser({email: '[email protected]', password:'safe-password',
                                     online: true})).toEqual({
      id: expect.any(Number),
      email: '[email protected]',
      password: 'safe-password'
    })
  })
});

user.serive.ts

constructor(@InjectModel('User') private readonly userModel: Model<User>){}

  async createUser(createUserDTO: CreateUserDTO): Promise<User>{
    const newUser = new this.userModel(createUserDTO);
    return newUser.save();
  }

Error

CodePudding user response:

new this.userModel is expected to be an instantiable object (an object that has a constructor and can be used to instantiate a new object instance, like a class or a constructor function). However the mockUsersModel that you are passing as an argument for the @InjectModel('User') decorator is not an instantiable object. Hence the invocation of new throws an error.

Given your use case, this is best fixed by assigning a constructor function to mockUsersModel as follows:

const mockUsersModel = function() {
  save: jest.fn().mockImplementation((user) => Promise.resolve({id: Date.now(), ...user}))
};
  • Related