Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/41.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 如何为单元测试模拟矩.utc()?_Node.js_Unit Testing_Mocking_Momentjs - Fatal编程技术网

Node.js 如何为单元测试模拟矩.utc()?

Node.js 如何为单元测试模拟矩.utc()?,node.js,unit-testing,mocking,momentjs,Node.js,Unit Testing,Mocking,Momentjs,我刚从Node开始,现在正在编写一些单元测试。对于前两个函数,我有一个可以正常工作的函数,但现在我偶然发现了一个函数,其中包含moment.utc()。my function的简化版本如下所示: function calculate_x(positions, risk_free_interest){ let x = 0; for (let position of positions) { let expiry_in_years = get_expire_in_ye

我刚从Node开始,现在正在编写一些单元测试。对于前两个函数,我有一个可以正常工作的函数,但现在我偶然发现了一个函数,其中包含
moment.utc()
。my function的简化版本如下所示:

function calculate_x(positions, risk_free_interest){
    let x = 0;
    for (let position of positions) {
        let expiry_in_years = get_expire_in_years(moment.utc());
        if (expiry_in_years > 0){
            let pos_x = tools.get_x(expiry_in_years, risk_free_interest);
            x += pos_x;
        }
    }

    return x;
}
我尝试使用基本节点断言测试库对此进行测试:

"use strict";
const assert = require('assert');
let positions = [{this: 'is', a: 'very', large: 'object'}]; 
assert.strictEqual(calculate_x(positions, 1.8), 1.5);
由于运行此操作的时间(以及结果)总是不同的,因此此操作总是失败的

在Python中,我可以设置模拟类和对象。有没有一种方法可以在Node中解决此问题,而不将moment.utc()作为
计算函数的参数?
moment让您

如果要更改时刻所看到的时间,可以指定一个方法,该方法返回自Unix纪元(1970年1月1日)以来的毫秒数

默认值为:

moment.now = function () {
    return +new Date();
}
调用
moment()
时将使用该日期,在
format()
中省略标记时使用当前日期。通常,任何需要当前时间的方法都会在引擎盖下使用该时间


因此,您可以重新定义
时刻。现在
要在代码执行
时刻.utc()时获得自定义输出

如果您只想覆盖utc函数,而其他功能都不起作用,请尝试将其添加到测试套件中

moment.prototype.utc = sinon.stub().callsFake(() => new Date(1970, 1, 1, 0, 0));


你需要类似的东西吗?sinon是一个很棒的测试库esp for node,你也可以在里面模拟/更改计时器@VincenzoC-真棒!正是我需要的!如果你添加你的评论作为回答,我可以接受。@kramer65好的,我将把它放在回答中:)
moment.prototype.utc = sinon.stub().callsFake(() => new Date(1970, 1, 1, 0, 0));
moment.prototype.utc = jest.fn().mockReturnValue(new Date(1970, 1, 1, 0, 0));