Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing mongoose models with NestJS

Tags:

I'm using the mongoose module from NestJS so I have my schema and an interface, and in my service I use @InjectModel to inject my model. I do not realize how I can mock the model to inject in my service.

My service looks like this:

    @Injectable()
    export class AuthenticationService {

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

        async createUser(dto: CreateUserDto): Promise<User> {
            const model = new this.userModel(dto);
            model.activationToken = this.buildActivationToken();
            return await model.save();
          }
    }

and in my service test, I have this:

    const mockMongooseTokens = [
      {
        provide: getModelToken('User'),
        useValue: {},
      },
    ];

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

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

But when I run the test I got this error:

    TypeError: this.userModel is not a constructor

I would also like to get my model to perform unit tests over it, as is shown in this article


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!