我试图嘲弄与jest
猫鼬的模式,但越来越Cannot create property 'constructor' on number '1'
错误。我能够通过创建2个文件如下图所示的项目重现该问题。有没有一种方法来嘲笑与jest
猫鼬模式?
./model.就是
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const schema = new Schema({
name: String
})
module.exports = mongoose.model('Test', schema)
./model.test.就是
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
另一解决方案是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"
。
好吧,我有同样的问题,所以我创作这个包来解决这个问题: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 });
})
});
检出的测试文件夹中有更多的例子:https://github.com/alonronin/mockingoose/blob/master/___tests___/index.test.js
没有连接是对数据库进行!
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