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

查看:26
本文介绍了如何模拟 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 中解决这个问题,而无需将 moment.utc() 作为 calculate_x() 函数的参数?

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 让你改变时间来源

如果你想改变 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.now 以在代码执行 moment.utc() 时获得自定义输出.

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

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

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