使用间谍和sinon js

时间:2017-01-24 08:47:45

标签: javascript sinon

我有以下功能

function trim(value) {
  if (typeof value === 'string') {
    if (String.prototype.trim) {
      value = value.trim();
    } else {
      value = value.replace(/^\s+|\s+$/g, '');
    }

    return value;
  }
} 

我正在为它编写单元测试,以确保在调用trim时调用native String.prototype.trim(如果可用)。我试图使用间谍来确保它被称为

var Util = require('test/util/methods');

it('should use native trim', function() {
    var spy = sinon.spy(String.prototype, 'trim');
    Util.trim('test string   ');
    expect(spy.calledOnce).toEqual(true);
    expect(Util.trim('test string    ')).toEqual('test string');
    spy.restore();
  });

但我觉得我应该做的是,当调用trim时,我应该检查String.prototype.trim是否也被调用。

我将如何做到这一点?如果有人有任何指示,请同时告知,因为我想尽可能地获得它的测试方

由于

1 个答案:

答案 0 :(得分:1)

所以只打电话trim一次,然后再打两个expect

it('should use native trim', function() {
    var spy = sinon.spy(String.prototype, 'trim');
    expect(Util.trim('test string    ')).toEqual('test string');
    expect(spy.calledOnce).toEqual(true);
    spy.restore();
});