Jest mock moment() 返回特定日期 [英] Jest mock moment() to return specific date
问题描述
我知道这个问题已经被问过多次了.
I know this question has been asked multiple times.
但我找不到适合我的案例.
But I could not find the correct one for my case.
我想模拟 moment() 以返回特定日期.
I would like to mock the moment() to return a specific date.
首先,我嘲笑
jest.mock("moment", () => {
return (date: string) =>
jest.requireActual("moment")(date || "2021-01-01T00:00:00.000Z");
});
但是我使用了一些 moment 的属性,(例如moment.duration()...
)所以当像这样模拟时,它不起作用.
But I use some properties of moment, (moment.duration()...
for example) So when mock like this, it does not work.
下一步我尝试通过几种方式模拟 Date.now
:
Next I tried to mock Date.now
by several ways:
jest.spyOn(Date, "now").mockReturnValue(+new Date("2021-01-01T00:00:00.000Z"));
Date.now = jest.fn(() => +new Date("2021-01-01T00:00:00.000Z")
但是当这样做时,当调用 moment()
时它返回一个无效的日期.
But when doing this, when calling moment()
it returns an invalid date.
我不确定我做错了什么.
I'm not sure what I am doing wrong.
推荐答案
模拟 moment()
函数及其返回值.使用 jest.requireActual('moment')
获取原始模块.将其属性和方法复制到模拟的.
Mock the moment()
function and its returned value. Use jest.requireActual('moment')
to get the original module. Copy its properties and methods to the mocked one.
例如
index.js
:
import moment from 'moment';
export function main() {
const date = moment().format();
console.log('date: ', date);
const duration = moment.duration(2, 'minutes').humanize();
console.log('duration: ', duration);
}
index.test.js
:
import { main } from '.';
import moment from 'moment';
jest.mock('moment', () => {
const oMoment = jest.requireActual('moment');
const mm = {
format: jest.fn(),
};
const mMoment = jest.fn(() => mm);
for (let prop in oMoment) {
mMoment[prop] = oMoment[prop];
}
return mMoment;
});
describe('68209029', () => {
it('should pass', () => {
moment().format.mockReturnValueOnce('2021-01-01T00:00:00.000Z');
main();
});
});
测试结果:
PASS examples/68209029/index.test.js (8.914 s)
68209029
✓ should pass (20 ms)
console.log
date: 2021-01-01T00:00:00.000Z
at Object.main (examples/68209029/index.js:5:11)
console.log
duration: 2 minutes
at Object.main (examples/68209029/index.js:7:11)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 9.726 s
查看日志,我们正确模拟了 moment().format()
的返回值并继续使用 moment.duration(2, 'minutes' 的原始实现).humanize()
方法.
Take a look at the logs, we mocked the returned value of moment().format()
correctly and keep using the original implementation of moment.duration(2, 'minutes').humanize()
method.
这篇关于Jest mock moment() 返回特定日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!