Mocking Mongoose model with jest
An other solution is to spyOn
the model prototype
functions.
For example, this will make MyModel.save()
fail :
jest.spyOn(MyModel.prototype, 'save') .mockImplementationOnce(() => Promise.reject('fail update'))
You can use mockImplementationOnce
to not having to mockRestore
the spy. But you can also use mockImplementation
and use something like :
afterEach(() => { jest.restoreAllMocks()})
Tested with "mongoose": "^4.11.7"
and "jest": "^23.6.0"
.
ok, i had the same problem so i author this package to solve this problem:https://www.npmjs.com/package/mockingoose
this is how you can use it let's say this is your model:
import mongoose from 'mongoose';const { Schema } = mongoose;const schema = Schema({ name: String, email: String, created: { type: Date, default: Date.now }})export default mongoose.model('User', schema);
and this is your test:
it('should find', () => { mockingoose.User.toReturn({ name: 2 }); return User .find() .where('name') .in([1]) .then(result => { expect(result).toEqual({ name: 2 }); })});
checkout the tests folder for more examples:https://github.com/alonronin/mockingoose/blob/master/___tests___/index.test.js
no connections is made to the database!
Mockingoose seems to be a very nice solution. But I was also able to mock my model with Jest.mock()
function. At least create
method.
// in the module under the test I am creating (saving) DeviceLocation to DB// someBackendModule.js...DeviceLocation.create(location, (err) => {...});...
DeviceLocation model definition:
// DeviceLocation.jsimport mongoose from 'mongoose';const { Schema } = mongoose;const modelName = 'deviceLocation';const DeviceLocation = new Schema({...});export default mongoose.model(modelName, DeviceLocation, modelName);
DeviceLocation mock in the __mocks__
folder in the same folder as DeviceLocation
model:
// __mock__/DeviceLocation.jsexport default { create: (x) => { return x; },};
in the test file:
// test.js// calling the mock...jest.mock('../../src/models/mongoose/DeviceLocation');import someBackendModule from 'someBackendModule';...// perform the test