例如,我正在使用 moment,并且需要 stub 当前时间以始终返回 1/1/18。因此,当我调用 moment()
或 moment.now()
时,我应该收到一个时间设置为 1/1/18 的 moment 对象。
现在我可以覆盖 moment.now但由于模块缓存,任何其他使用 moment 的东西都会有这个 stub ,这不是我想要的。
所以我写了一个 momentWrapper 来复制 moment 的原型(prototype)并定义一个新的构造函数。问题是,当调用 moment()
时,它不使用 now
新定义的原型(prototype),因为我只是调用 moment 的构造函数。我需要复制 moment 并在我的新构造函数中更改它的 now
原型(prototype),我只是不知道该怎么做。
这是我到目前为止所拥有的:
/**
* Wraps moment so that alternate time can be set as the 'now' time.
* This idea was grabbed from fs-extra https://github.com/jprichardson/node-fs-extra
* @module lib/momentWrapper
*/
var moment = require('moment');
function momentWrapper() {
return moment.apply(this, arguments);
}
assign(momentWrapper, moment);
momentWrapper.prototype = Object.create(moment.prototype);
momentWrapper.prototype.now = newNow;
momentWrapper.prototype.constructor = momentWrapper;
function newNow() {
return +new Date('1995-12-17T03:24:00');
}
/**
* Loops through given arguments and assigns them to a object
* Credit: fs-extra https://github.com/jprichardson/node-fs-extra/blob/fab376ec2bd4d4420806644c1b37a7ac487d17ec/lib/util/assign.js
* @function assign
* @return {Object} Mutated object with copied keys
*/
function assign () {
const args = [].slice.call(arguments).filter(i => i);
const dest = args.shift();
args.forEach(src => {
Object.keys(src).forEach(key => {
if (key === 'now') {
dest[key] = newNow;
}
else {
dest[key] = src[key];
}
});
});
return dest;
}
module.exports = momentWrapper;
测试文件:
var momentWrapper = require('./momentWrapper');
var moment = require('moment');
console.log(momentWrapper()); // Not working
console.log(momentWrapper('12/25/18', 'MM/DD/YY')); // Working
console.log(momentWrapper(momentWrapper.now()).format()) // Working
console.log('----------------------------------------');
console.log(moment()); // Working not being overridden
console.log(moment(moment.now()).format()) // // Working not being overridden
输出:
moment("2018-01-27T15:56:50.928")
moment("2018-12-25T00:00:00.000")
1995-12-17T03:24:00-05:00
----------------------------------------
moment("2018-01-27T15:56:50.938")
2018-01-27T15:56:50-05:00
最佳答案
取决于您的用例,而不是使用包装器;您可以暂时用自定义 stub 替换 now
函数,当您使用完它后,只需将原来的 stub 放回去即可。
var moment = require("moment");
// prepare before testing
moment.originalNow = moment.now;
moment.now = () => +new Date('1995-12-17T03:24:00');
console.log([
moment().format(),
moment(moment.now()).format(),
moment('12/25/18', 'MM/DD/YY').format()
]);
// clean after testing
moment.now = moment.originalNow;
moment.originalNow = undefined;
console.log([
moment().format(),
moment(moment.now()).format()
]);
关于javascript - 如何使用包装模块覆盖现在时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48480563/