0

I have next Card model

export class Card extends Document {
@Prop({ required: true, immutable: true})
id: string;

@Prop({ required: true })
name: string;
...
export const CardSchema = SchemaFactory.createForClass(Card);
}

And test are freezing when i try to mock data in test by

import { INestApplication } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import * as request from 'supertest';
import { AppModule } from '../../../../src/app.module';
import { createAuthToken } from '../../../helpers/auth.helper';
import { Card } from '../../../../src/card/card.schema';
import { Model } from 'mongoose';
import { getModelToken } from '@nestjs/mongoose';
import mockingoose from 'mockingoose';

describe('GET /card:id', () => {
  let app: INestApplication;
  let cardModel: Model<Card>;

  beforeAll(async () => {
...
  });

  it('Should receive card data', async () => {
...
    mockingoose(cardModel).toReturn(_doc, 'findOne');
    return request(app.getHttpServer())
      .get('/card/test')
      .set('Content-Type', 'application/json')
      .set('Authorization', `Bearer ${createAuthToken(user)}`)
      .expect(200);
  })
  ...
});

i have controller, DTO and service for load entity.

here is console screen: test log screen

1 Answers1

0

This might be due to an interplay between different instances of 'mongoose'. Check if you have other instances of mongoose being imported in the module hierarchy.

I had an issue very similar to what you're describing. With multiple imports, a couple of them were loading mongoose objects that, together, when I added mockingoose, made the test cases hang indefinitely.

For instance, say module A imports/loads 'mongoose', then you import mockingoose that also requires/loads 'mongoose' (and mocks a mongoose connection). For some reason, there's a weird interplay between these [possibly] conflicting mongoose references that make the test cases hang indefinitely without response.

The way I solved the issue was refactoring the code so that, when using mockingoose, the only place I refer to mongoose is in my test file. All my imported modules do not refer to mongoose objects. And you can do that by leveraging a good design with dependency injection.

Bruno da Silva
  • 131
  • 2
  • 4