如何为单元测试模拟moment.utc()? [英] How to mock moment.utc() for unit tests?

查看:99
本文介绍了如何为单元测试模拟moment.utc()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm just starting out with Node and I'm now writing some unit tests. For the first couple functions I have that works ok, but I now hit upon a function which includes moment.utc() in it. A simplified version of my function looks like this:

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

我尝试使用基本节点断言测试库进行测试:

I try to test this using the basic node assert testing lib:

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

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

Since the times at which this is run (and thus the result) will always be different this will always fail.

在Python中,我可以设置模拟类和对象.有没有一种方法可以在Node中解决这个问题而又不给calculate_x()函数一个参数moment.utc()?

In Python I can set mock classes and objects. Is there a way that I can solve this problem in Node without giving the moment.utc() as an argument to the calculate_x() function?

推荐答案

时刻让您更改时间来源

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

If you want to change the time that Moment sees, you can specify a method that returns the number of milliseconds since the Unix epoch (January 1, 1970).

默认值为:

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

在调用moment()时将使用此名称,在format()中省略令牌时将使用当前日期.一般来说,任何需要当前时间的方法都可以在后台使用.

This will be used when calling moment(), and the current date used when tokens are omitted from format(). In general, any method that needs the current time uses this under the hood.

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

So you can redefine moment.now to get the custom output when you code executes moment.utc().

这篇关于如何为单元测试模拟moment.utc()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆