【问题标题】:sinon mock not catching callssinon mock 不接电话
【发布时间】:2017-06-16 13:53:45
【问题描述】:

我很难理解我做错了什么。

我有一个这样的 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)

我已经检查过(添加了一个 console.log),它正在调用我在测试中定义的对象。

【问题讨论】:

  • 我对 ES2015 的 async/await 结构不是很熟悉,但是在 ES5 中,您需要向测试函数添加一个参数回调函数,该函数将在您的测试完成后调用。这是隐含的吗?或者,我猜如果将 async 放在函数前面意味着返回一个 Promise,那么这应该可以工作,因为 Mocha 支持向测试函数返回 Promise。

标签: javascript unit-testing mocking sinon


【解决方案1】:

我在本地运行并阅读了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;
    });
  });
});

【讨论】:

  • 谢谢克里斯蒂安。我改变了我的测试,但想了解为什么它没有工作,即使看起来一切都是正确的:/
  • @RaquelGuimarães 我也试过这个。但对我来说,实际的函数被调用了。
猜你喜欢
  • 2015-08-21
  • 1970-01-01
  • 2020-10-21
  • 1970-01-01
  • 2018-09-10
  • 1970-01-01
  • 2019-07-07
  • 2021-07-23
相关资源
最近更新 更多