DevMJ
DevMJ

Reputation: 11

Nestjs e2e testing with mocking mongoose model

I am writing end to end test for my NestJS + mongoose application with supertest. I am able to mock mongoose apis such as find(), delete() etc. But with mongoose save() api, for code this.CatModel(CatObject), mocking is not working. I dont have mongodb for test system, so I need to mock it.

cat.e2e-spec.ts

describe('cat apis', () => {
    let app: INestApplication;

    beforeAll(async () => {
    const module = await Test.createTestingModule({
        imports: [CatModule]
    })
    .overrideProvider(getModelToken('Cat'))
    .useValue(mockCatModel)
    .compile();

    app = module.createNestApplication();
      server = app.getHttpServer();
      await app.init();
    });

    it(`POST /cat `, async () => {
        return await request(server)
            .post('/cat')
            .send(newCatPayload)
            .set('Accept', 'application/json')
            .expect(201)
            .expect(({ body }) => {
                expect(body).toEqual(expectedResponse);
            });
    });
});

catModel.ts

export const mockCatModel = {
    find: (obj) => {
        return [catMock];
    },

    save : (cat) => {
        return cat;
    }
};

cat.service.ts

public async createCat(catObject: CreateCatDto, user): Promise<ICat> {
    const oCat = this.catModel(catObject);
    oCat.user = user;
    return await oCat.save();
}

this.catModel.find() works fine but, this.catModel() throws Error: 'this.catModel is not a function'.

I tried in catModel.ts, adding below function,

function : (a) => {return a;}

but did not work. Please help if anyone knows how to mock this.catModel(catObject).

Upvotes: 0

Views: 2627

Answers (1)

Steve Rock
Steve Rock

Reputation: 372

You can try it. Or could)

  let app: INestApplication;
  let testingModule: TestingModule;
  let spyService: CatsService;

  beforeEach(async () => {
    testingModule = await Test.createTestingModule({
      controllers: [CatsController],
      providers: [
        {
          provide: CatsService,
          useFactory: () => ({
            findAll: jest.fn((obj) => [catMock]),
            save: jest.fn((cat) => cat)
          }),
        },
      ],
    }).compile();

    spyService = testingModule.get(CatsService);

    app = testingModule.createNestApplication();
    await app.init();
  });

Upvotes: 1

Related Questions