我正在使用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()
进行存根,但是遇到了同样的错误。也许我在模型定义上做错了什么?我该如何解决?