惩戒猫鼬模型开玩笑

问题描述 投票:11回答:3

我试图嘲弄与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

node.js mongodb jestjs
3个回答
8
投票

另一解决方案是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"


8
投票

好吧,我有同样的问题,所以我创作这个包来解决这个问题: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

没有连接是对数据库进行!


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
© www.soinside.com 2019 - 2024. All rights reserved.