Reputation: 11
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.
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);
});
});
});
export const mockCatModel = {
find: (obj) => {
return [catMock];
},
save : (cat) => {
return cat;
}
};
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
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