我有以下功能
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
也被调用。
我该怎么做?
所以只拨打
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();
});