如何模拟 dayjs 链接方法

How to mock dayjs chained methods

我有这个 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");
    }),
  })),
}));

两者都不起作用。有人有建议吗?

假设您正在尝试创建一个不考虑给定日期参数的一致输出,您可以像这样创建 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"`);
  });
});

example on github

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();