【发布时间】: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