【问题标题】:Cannot stub non-existent property "create" of a mongoose document不能存根不存在的属性“创建”猫鼬文档
【发布时间】:2021-01-07 11:43:49
【问题描述】:

我正在使用 Sinon 为我的 express 应用程序编写单元测试。我有一个Log 模型:

import { Schema, model } from 'mongoose';

const LogSchema = new Schema({
    content: {
        type: String,
        required: true,
    },

    date: {
        type: Date,
        default: Date.now,
    },
});

const Log = model('Log', LogSchema);

export default Log;

还有一个LogController

import Log from '../models/Log';

class LogController {
    static async create(content) {
        await Log.create({ content });
    }
}

export default LogController;

我正在尝试为LogController.create() 编写测试。

import { createSandbox } from 'sinon';
import Log from '../../../src/models/Log';
import LogController from '../../../src/controllers/LogController';

describe('LogController', () => {
    let sandbox;
    let createStub;

    beforeEach(() => {
        sandbox = createSandbox();

        createStub = sandbox.stub(Log, 'create');
    });

    describe('create()', () => {
        it('should create a Log with the given content', async () => {
            await LogController.create('Bob Lob Law is on the house');

            expect(createStub.calledWith({ content: 'Bob Lob Law is on the house' })).to.be.true;
        });
    });

然后我得到TypeError: Cannot stub non-existent property create,这意味着Log 没有create 方法。这很奇怪,因为我有其他控制器完全像这样进行测试并且它们不会抛出任何错误。我也尝试使用Log.create = sandbox.stub() 将其存根,但我得到了同样的错误。也许我在模型定义上做错了什么?我该如何解决这个问题?

【问题讨论】:

    标签: node.js express mongoose sinon


    【解决方案1】:

    Sinon 认为您出于某种原因(而不是 model.create)尝试存根 object.create 可能是因为 model.create 返回了一个承诺,但您的存根没有返回任何内容。你需要改变

    createStub = sandbox.stub(Log, 'create');
    

    createStub = sandbox.stub(Log, 'create').resolves();
    

    【讨论】:

      猜你喜欢
      • 2021-07-05
      • 1970-01-01
      • 2017-07-05
      • 2016-10-06
      • 2017-12-05
      • 2021-02-12
      • 1970-01-01
      • 2016-06-17
      • 1970-01-01
      相关资源
      最近更新 更多