我很难理解我做错了什么。
我有一个这样的JS类:
export default class A {
constructor(repository) {
this._repository = repository;
}
async process(date) {
// ...
this._repository.writeToTable(entry);
}
}
我正在尝试编写一个测试,使用sinon.mock
模拟存储库
这是我到目前为止所拥有的:
describe('A', () => {
describe('#process(date)', () => {
it('should work', async () => {
const repository = { writeToTable: () => {} };
const mock = sinon.mock(repository);
const a = new A(repository);
await a.process('2017-06-16');
mock.expects('writeToTable').once();
mock.verify();
});
});
});
但它总是说不通
ExpectationError: Expected writeToTable([...]) once (never called)
我已经检查(添加了一个控制台.log(,它正在调用我在测试中定义的对象。
我在本地运行了这个并阅读了 sinonjs.org 的文档,你似乎做对了一切。
我尝试使用spy
重写您的示例,最终得到了这样的东西以获得通过的测试:
import sinon from "sinon";
import { expect } from "chai";
import A from "./index.js";
describe("A", () => {
describe("#process(date)", () => {
it("should work", async () => {
const repository = { writeToTable: sinon.spy() };
const a = new A(repository);
await a.process("2017-06-16");
expect(repository.writeToTable.calledOnce).to.be.true;
});
});
});