【问题标题】:sinon spy not wrapping method in asynchronous callbacksinon spy 不在异步回调中包装方法
【发布时间】:2015-11-20 08:59:41
【问题描述】:

sinon.spy(object, method) 似乎没有按预期包装我的 object#method。

(我有一种不安的感觉,我看到了与 herehere 描述的相同的问题,但我不明白为什么会这样。我在调用 @ 之前实例化了我的对象987654324@ 和 AFAIK,我没有使用任何缓存对象。)

这是完整的测试文件:

var 
AmbitParser = require('../lib/parsers/ambit-parser'),
expect = require('chai').expect,
sinon = require('sinon');

describe('AmbitParser', function() {
    var ambit_parser = new AmbitParser();

    describe('#extractLineItems()', function() {

        it('calls extractLineItems once', function(done) {
            var spy = sinon.spy(ambit_parser, 'extractLineItems');

            ambit_parser.parseBills(function gotBills(err, bills) {
                expect(ambit_parser.extractLineItems.callCount).to.equal(1); // => expected undefined to equal 1
                expect(spy.callCount).to.equal(1);                           // => expected 0 to equal 1
                done();
            });

            ambit_parser.extractLineItems.restore();
        });                     // calls extractLineItems once
    });                         // #extractLineItems
});                             // AmbitParser

expect(ambit_parser.extractLineItems.callCount).to.equal(1); 的调用导致“预期未定义等于1”,如果我将其更改为expect(spy.callCount).to.equal(1);,我会得到“预期0 等于1”。

总的来说,这让我认为对 sinon.spy(...) 的调用没有按预期包装 ambit_parser.extractLineItems 方法,但我不明白为什么会这样。

【问题讨论】:

    标签: javascript mocha.js sinon


    【解决方案1】:

    问题在于调用restore() 的位置:它不应该在测试函数的主体中。而是将其放在 after() 块中。

    发生的情况是,restore() 方法在测试开始后立即被调用,所以在执行回调时,被监视的方法已经恢复,所以 sinon 会报告该方法从未被调用过.

    对原始代码的以下修改将按预期工作:

    describe('AmbitParser', function() {
        var ambit_parser = new AmbitParser();
    
        describe('#extractLineItems()', function() {
    
            before(function() {
                sinon.spy(ambit_parser, 'extractLineItems');
            });
            after(function() {
                ambit_parser.extractLineItems.restore();
            });
    
            it('calls extractLineItems once', function(done) {
                ambit_parser.parseBills(function gotBills(err, bills) {
                    expect(ambit_parser.extractLineItems.callCount).to.equal(1);
                    done();
                });
            });                     // calls extractLineItems once
        });                         // #extractLineItems
    });                             // AmbitParser
    

    故事的寓意:确保只有在任何回调完成后才调用reset()

    【讨论】:

      猜你喜欢
      • 2018-02-23
      • 1970-01-01
      • 2019-09-11
      • 2014-05-20
      • 2016-12-23
      • 2015-12-14
      • 1970-01-01
      • 2014-11-20
      • 1970-01-01
      相关资源
      最近更新 更多