【问题标题】:Sinon spy on all method callsSinon 监视所有方法调用
【发布时间】:2017-05-09 16:47:58
【问题描述】:

我正在尝试测试一个特定的实例方法是否至少被调用过一次。使用mochasinon。有 2 个类:ABB#renderA#render 内部被调用。无法访问测试文件中的 B 实例。

sinon.spy B.prototype, 'render'
@instanceA.render
B.prototype.render.called.should.equal true
B.prototype.render.restore()

这是一种正确的方法吗? 谢谢

【问题讨论】:

    标签: testing coffeescript sinon


    【解决方案1】:

    你应该这样做:

    const chai = require('chai');
    const sinon = require('sinon');
    const SinonChai = require('sinon-chai');
    
    chai.use(SinonChai);
    chai.should();
    
    /**
     * Class A
     * @type {B}
     */
    class A {
    
      constructor(){
          this.b = new B();
      }
    
    
      render(){
        this.b.render();
      }
    }
    
    
    /**
     * Class B
     * @type {[type]}
     */
    class B {
    
      constructor(){
    
      }
    
      render(){
      }
    }
    
    
    
    context('test', function() {
    
      beforeEach(() => {
        if (!this.sandbox) {
          this.sandbox = sinon.sandbox.create();
        } else {
          this.sandbox.restore();
        }
      });
    
      it('should pass',
        (done) => {
    
          const a = new A();
    
          const spyA = this.sandbox.spy(A.prototype, 'render');
          const spyB = this.sandbox.spy(B.prototype, 'render');
    
          a.render();
    
          spyA.should.have.been.called;
          spyB.should.have.been.called;
    
          done();
        });
    
    });
    

    你的假设是正确的。您在类的原型级别添加间谍。希望对你有帮助:)

    【讨论】:

      猜你喜欢
      • 2020-05-23
      • 2015-05-13
      • 1970-01-01
      • 2019-06-28
      • 2015-06-30
      • 2021-11-11
      • 2018-08-19
      • 2016-01-02
      • 1970-01-01
      相关资源
      最近更新 更多