我无法模拟moment()或moment().format函数。我有几个州,currentDateMoment和currentDateFormatted的设置如下。
currentDateMoment: moment() //2019-04-23T17:45:26.339Z
currentDateFormatted: moment().format('MM-DD-YYYY').valueOf() //"04-23-2019"我试图在快照测试中模拟moment()和moment().format,以返回特定的日期,但无法做到。已在下面尝试。
jest.mock('moment', () => () => '2018–01–30T12:34:56+00:00');
jest.mock('moment', () => ({
constructor: () => '2018–01–30T12:34:56+00:00'
}));
jest.mock('moment', () => () => ({ format: () => '01–30-2018' }));发布于 2020-05-07 21:45:14
模拟moment()及其使用的任何函数(例如.day()、.format())的最简单方法是更改moment()在幕后使用的Date
将下面的代码片段添加到测试文件中
Date.now = jest.fn(() => new Date("2020-05-13T12:33:37.000Z"));
这使得无论何时在测试中调用moment(),moment()都会认为今天是2020年5月13日星期三
发布于 2020-03-03 18:42:20
你可以模拟Moment来返回一个特定的日期,这样format就不需要被模拟了。
jest.mock('moment', () => {
return () => jest.requireActual('moment')('2020-01-01T00:00:00.000Z');
});这样,对Moment()的任何调用都将始终返回日期设置为2020-01-01 00:00:00的moment对象
下面是一个示例,其中包含一个函数,该函数返回明天的日期以及此函数的测试。
const moment = require('moment');
const tomorrow = () => {
const now = moment();
return now.add(1, 'days');
};
describe('tomorrow', () => {
it('should return the next day in a specific format', () => {
const date = tomorrow().format('YYYY-MM-DD');
expect(date).toEqual('2020-01-02');
});
});发布于 2019-11-12 17:40:37
以下是解决方案:
index.ts
import moment from 'moment';
export function main() {
return {
currentDateMoment: moment().format(),
currentDateFormatted: moment()
.format('MM-DD-YYYY')
.valueOf()
};
}index.spec.ts
import { main } from './';
import moment from 'moment';
jest.mock('moment', () => {
const mMoment = {
format: jest.fn().mockReturnThis(),
valueOf: jest.fn()
};
return jest.fn(() => mMoment);
});
describe('main', () => {
test('should mock moment() and moment().format() correctly ', () => {
(moment().format as jest.MockedFunction<any>)
.mockReturnValueOnce('2018–01–30T12:34:56+00:00')
.mockReturnValueOnce('01–30-2018');
expect(jest.isMockFunction(moment)).toBeTruthy();
expect(jest.isMockFunction(moment().format)).toBeTruthy();
const actualValue = main();
expect(actualValue).toEqual({ currentDateMoment: '2018–01–30T12:34:56+00:00', currentDateFormatted: '01–30-2018' });
});
});100%覆盖率的单元测试结果:
PASS src/stackoverflow/55838798/index.spec.ts
main
✓ should mock moment() and moment().format() correctly (7ms)
----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
index.ts | 100 | 100 | 100 | 100 | |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 3.795s, estimated 8s源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/55838798
https://stackoverflow.com/questions/55838798
复制相似问题