如何模拟moment.utc()进行单元测试?

kra*_*r65 10 unit-testing mocking node.js momentjs

我刚开始使用Node,我现在正在编写一些单元测试.对于前几个功能我可以正常工作,但我现在遇到了一个包含moment.utc()在其中的功能.我的函数的简化版本如下所示:

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;
}
Run Code Online (Sandbox Code Playgroud)

我尝试使用基本节点断言测试lib来测试它:

"use strict";
const assert = require('assert');
let positions = [{this: 'is', a: 'very', large: 'object'}]; 
assert.strictEqual(calculate_x(positions, 1.8), 1.5);
Run Code Online (Sandbox Code Playgroud)

由于运行它的时间(以及结果)总是不同,因此总是会失败.

在Python中,我可以设置模拟类和对象.有没有办法让我可以在Node中解决这个问题而不将moment.utc()作为calculate_x()函数的参数?

Vin*_*zoC 29

Moment让你改变时间源

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

默认为:

moment.now = function () {
    return +new Date();
}
Run Code Online (Sandbox Code Playgroud)

这将在调用时使用moment(),并且当省略标记时使用的当前日期format().通常,任何需要当前时间的方法都会使用它.

因此,您可以moment.now在代码执行时重新定义以获取自定义输出moment.utc().