How to mock dayjs chained methods

Viewed 8760

I have this dayjs objects:

const today = dayjs.utc(date).startOf("day")

I am trying to mock it using jest but to no avail. Here is the approach I tried:

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

I also tried this:

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");
    }),
  })),
}));

Both are not working. Anyone got an advice?

2 Answers

Presuming you're trying to create a consistent output disregarding the given date argument, you can create Node Module mock like this:

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;

and then in your tests within the src folder dayjs.utc will always be using the mocked date

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 works great for this, no intense mocking code required.

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

Remember to clear the mock after your test with: MockDate.reset();

Related