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

时间:2017-10-23 14:29:51

标签: node.js unit-testing mocking 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;
}

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

"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()作为calculate_x()函数的参数?

3 个答案:

答案 0 :(得分:19)

Moment让你Change Time Source

  

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

     

默认为:

moment.now = function () {
    return +new Date();
}
     

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

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

答案 1 :(得分:1)

如果您只想覆盖 utc 函数而没有其他任何工作,请尝试将其添加到您的测试套件中

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

答案 2 :(得分:-1)

const moment = require('moment'); 
const time = moment().valueOf();
moment.now = jest.fn().mockReturnValue(time);
相关问题