gpt4 book ai didi

javascript - 使用spy和sinon js

转载 作者:太空宇宙 更新时间:2023-11-04 16:06:28 27 4
gpt4 key购买 nike

我有以下功能

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(如果可用)。我正在尝试使用 spy 来确保它被调用

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();
});

关于javascript - 使用spy和sinon js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41823661/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com