我有今天的对象:
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");
}),
})),
}));两者都不起作用。有人有什么建议吗?
发布于 2020-07-15 07:02:25
假设您试图创建一个一致的输出,而不考虑给定的日期参数,您可以创建如下所示的节点模块模拟:
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"`);
});
});发布于 2022-11-29 10:06:49
我使用的是插件customParseFormat,我只是像这样模仿:
jest.mock('dayjs/plugin/customParseFormat', () => ({
default: jest.requireActual('dayjs/plugin/customParseFormat'),
}));对我来说很管用。
https://stackoverflow.com/questions/62898345
复制相似问题