【发布时间】:2020-07-06 13:02:55
【问题描述】:
我需要使用 jest 和 moment 进行一些测试。一些导入的函数适用于当前日期 (moment() )。但是我似乎无法找到一种始终运行相同日期来测试或模拟时刻构造函数的方法,例如在时刻('2020-07-05')的固定时刻日期,即使当天是 2020-07-10,因此测试应始终在第 5 天以下运行。
我的 ./UtilsModule 文件:
import moment from 'moment'
export const getIntervalDates = groupOfDates => {
const CURRENT_DATE = moment().format('YYYY-MM-DD');
return getDates(CURRENT_DATE, groupOfDates ) //another function that does some extra processing;
};
export const nextDates = (date, group) => {
let newDate= getIntervalDates(group);
}
我的 test.js 文件,以及我尝试的内容:
import { nextDates ,getIntervalDates } from '../UtilsModule';
it('testing function', () => {
const PAYLOAD = {...};
const DATE= '2020-07-20';
const SpyGetIntervalDates = jest.spyOn(UtilsModule, 'getIntervalDates');
SpyGetIntervalDates.mockImplementation(() => Promise.resolve({ minAge: '2020-08-04' }));
const nextDate = UtilsModule.nextDates(DATE, PAYLOAD);
expect(nextDate).toEqual({ minDate: '2020-11-04' });
});
我也试过了,但我不能让它工作:
jest.mock('moment', () => {
return () => jest.requireActual('moment')('2020-07-04');
});
and
global.moment = jest.fn(moment('2021-07-04'));
【问题讨论】:
-
moment是在哪里定义的? jest.mock 能不能影响就看这个了。 -
我在我的 utilsModule 中导入了时刻
-
UtilsModule 是导入的?.. 请提供stackoverflow.com/help/mcve 可以重现问题。目前还不清楚你的结果会发生什么,也不清楚如何解决它。一般来说, jest.mock 应该可以工作。
标签: javascript unit-testing testing jestjs momentjs