使用spy和Sinon.js

问题描述 投票:0回答:1

我有以下功能

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

    return value;
  }
} 

我正在为其编写一个单元测试,以确保当

trim
被称为本机时
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
也被调用。

我该怎么做?

javascript sinon
1个回答
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();
});
© www.soinside.com 2019 - 2024. All rights reserved.