我有这个dayjs对象:
const today = dayjs.utc(date).startOf("day")
我试图用玩笑来嘲笑它,但无济于事。 这是我尝试的方法:
jest.mock("dayjs", () => ({
extend: jest.fn(),
utc: jest.fn((...args) => {
const dayjs = jest.requireActual("dayjs");
dayjs.extend(jest.requireActual("dayjs/plugin/utc"));
return dayjs
.utc(args.filter((arg) => arg).length > 0 ? args : mockDate)
.startOf("day");
}),
startOf: jest.fn().mockReturnThis(),
}));
我也尝试过:
jest.mock("dayjs", () => ({
extend: jest.fn(),
utc: jest.fn((...args) => ({
startOf: jest.fn(() => {
const dayjs = jest.requireActual("dayjs");
dayjs.extend(jest.requireActual("dayjs/plugin/utc"));
return dayjs
.utc(args.filter((arg) => arg).length > 0 ? args : mockEventData)
.startOf("day");
}),
})),
}));
两者均不起作用。有人有建议吗?
答案 0 :(得分:1)
MockDate 非常适合这个,不需要大量的模拟代码。
https://www.npmjs.com/package/mockdate
import MockDate from 'mockdate'
import dayjs from 'dayjs'
import utc from 'dayjs/plugin/utc'
dayjs.extend(utc)
MockDate.set('2000-11-22')
console.log(dayjs.utc().format())
// >>> 2000-11-22T00:00:00Z
记住在测试后清除模拟:
MockDate.reset();
答案 1 :(得分:0)
假设不考虑给定日期参数而试图创建一致的输出,则可以这样创建Node Module mock:
src/__mocks__/dayjs.js
const mock = jest.genMockFromModule('dayjs');
const dayjs = jest.requireActual("dayjs");
const utc = jest.requireActual('dayjs/plugin/utc')
dayjs.extend(utc);
mock.utc = jest.fn().mockReturnValue(dayjs.utc(new Date('1995-12-17T03:24:00')))
module.exports = mock;
,然后在您的测试中,src
文件夹dayjs.utc
中将始终使用模拟日期
src/today.spec.js
const today = require("./today");
const dayjs = require("dayjs");
describe("today", () => {
let result;
beforeAll(() => {
result = today();
});
it("should be called with a date", () => {
expect(dayjs.utc).toHaveBeenCalledWith(expect.any(Date));
});
it("should return consistent date", () => {
expect(result).toMatchInlineSnapshot(`"1995-12-17T00:00:00.000Z"`);
});
});