[英]Mocking Mongoose model with jest
我试图用jest
模拟一个猫鼬模型,但是得到了Cannot create property 'constructor' on number '1'
错误Cannot create property 'constructor' on number '1'
。 我能够通过使用下面显示的2个文件创建项目来重现该问题。 有没有办法用jest
模拟猫鼬模型?
./model.js
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const schema = new Schema({
name: String
})
module.exports = mongoose.model('Test', schema)
./model.test.js
jest.mock('./model')
const Test = require('./model')
// Test.findOne.mockImplementation = () => {
// ...
// }
错误:
FAIL ./model.test.js
● Test suite failed to run
TypeError: Cannot create property 'constructor' on number '1'
at ModuleMockerClass._generateMock (../../jitta/sandbox/rest_api/node_modules/jest-mock/build/index.js:458:34)
at Array.forEach (native)
at Array.forEach (native)
at Array.forEach (native)
更新:
似乎是一个开玩笑的错误。 https://github.com/facebook/jest/issues/3073
好吧,我有同样的问题,所以我创作这个包来解决这个问题: https : //www.npmjs.com/package/mockingoose
这就是你如何使用它让我们说这是你的模型:
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);
这是你的考验:
it('should find', () => {
mockingoose.User.toReturn({ name: 2 });
return User
.find()
.where('name')
.in([1])
.then(result => {
expect(result).toEqual({ name: 2 });
})
});
检查tests文件夹以获取更多示例: https : //github.com/alonronin/mockingoose/blob/master/___tests___/index.test.js
没有连接数据库!
另一种解决方案是spyOn
模型prototype
函数。
例如,这将使MyModel.save()
失败:
jest.spyOn(MyModel.prototype, 'save')
.mockImplementationOnce(() => Promise.reject('fail update'))
你可以使用mockImplementationOnce
来不用mockRestore
这个间谍。 但是你也可以使用mockImplementation
并使用类似的东西:
afterEach(() => {
jest.restoreAllMocks()
})
用"mongoose": "^4.11.7"
"jest": "^23.6.0"
测试"mongoose": "^4.11.7"
和"jest": "^23.6.0"
。
Mockingoose似乎是一个非常好的解决方案。 但我也能用Jest.mock()
函数模拟我的模型。 至少create
方法。
// in the module under the test I am creating (saving) DeviceLocation to DB
// someBackendModule.js
...
DeviceLocation.create(location, (err) => {
...
});
...
DeviceLocation模型定义:
// DeviceLocation.js
import mongoose from 'mongoose';
const { Schema } = mongoose;
const modelName = 'deviceLocation';
const DeviceLocation = new Schema({
...
});
export default mongoose.model(modelName, DeviceLocation, modelName);
与DeviceLocation模型位于同一文件夹中的__mocks__
文件夹中的DeviceLocation
模拟:
// __mock__/DeviceLocation.js
export default {
create: (x) => {
return x;
},
};
在测试文件中:
// test.js
// calling the mock
...
jest.mock('../../src/models/mongoose/DeviceLocation');
import someBackendModule from 'someBackendModule';
...
// perform the test
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.