使用Sinon.js存根Performance.now()

时间:2020-03-20 18:47:17

标签: javascript ember.js sinon qunit ember-qunit

我正在用Ember-qunit编写单元测试。我想在performance.now上设置一个自定义值。

我尝试了sinon.stub(performance,'now', 60000);,但这没有用。我得到TypeError: stub(obj, 'meth', fn) has been removed.

如何使用sinon.js存根Performance.now()?

谢谢

2 个答案:

答案 0 :(得分:0)

由于我不熟悉60000,不确定您的第三个参数(performance.now())应该是什么,但这不是对Sinon.stub()there is no 3rd parameter )。但是根据文档,您应该能够捕获存根函数,然后在其上调用方法以指示所需的返回值:

const stub = sinon.stub(performance, 'now');
stub.returns(60000);

然后,在调用存根时,您应该得到:

console.log( stub() );  // 60000

您可以在此jsfiddle example中看到此功能。

答案 1 :(得分:0)

创建一个像这样的全局对象:

global.performance = {
   now() {
    return <returning_value>; // use Date.now() or any value
};

现在您可以访问performance.now()