繁体   English   中英

Mock DayJs 默认 function 及其链式方法

[英]Mock DayJs default function along with its chained methods

我正在尝试模拟具有特定日期和时间的dayjs()默认值 function,并且还想模拟其嵌套方法,即utc() &。 添加()

到目前为止,这是我尝试过的:

abc.ts:

getEarliestDate() {
    const {
        minHour,
        maxHour
    } = operatingHours;
    const earliestDateTime = dayjs().add(sla + 1, 'minute');
    const earliestDateTimeUTC = earliestDateTime.utc();

    return dayjs().add(121, 'minute').format('YYYY-MM-DD HH:mm');
}

abc.test.ts:

import { abc } from '../../src/common/serviceFactory';
import dayjs from 'dayjs';

jest.mock('dayjs', () =>
  jest.fn((...args) => jest.requireActual('dayjs')(args.filter((arg) => arg).length > 0 ? args : '2020-08-12')),
);

jest.mock('dayjs', () => ({
  default: jest.requireActual('dayjs')(`2020-08-18 12:00:00`),
  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 : '12:00:00').startOf('day');
  }),
  add: jest.requireActual('dayjs')(`2020-08-18 12:00:00`),
}));

describe('getEarliestDate Function', () => {
  it('should return earliest date response', () => {
    const earliestDate = abc.getEarliestDate();
    expect(earliestDate).toMatch(dayjs().add(121, 'minute').format('YYYY-MM-DD HH:mm'));
  });

但是得到这个: TypeError: dayjs_1.default is not a function

任何帮助/建议表示赞赏。

对于 dayjs 的基本操作,此代码有效:

jest.mock('dayjs', () => jest.fn((...args) => jest.requireActual('dayjs')(args.filter((arg) => arg).length > 0 ? args : '2020-08-12')),);

当“2020-08-12”是您要模拟的日期时。

MockDate 对此非常有用,不需要密集的 mocking 代码。

https://www.npmjs.com/package/mockdate

import MockDate from 'mockdate'
import dayjs from 'dayjs'

MockDate.set('2000-11-22')
console.log(dayjs.format())

// >>> 2000-11-22T00:00:00Z

请记住在测试后清除模拟: MockDate.reset();

我认为问题是模拟模块的default function 应该是 function 而不是dayjs()的返回结果。 尝试如下操作:

jest.mock('dayjs', () => ({
  default: jest.fn((...args) => {
    const yourDay = jest.requireActual('dayjs')(args.filter((arg) => arg).length > 0 ? args : '2020-08-11');
    // Mock add function
    yourDay.add = jest.fn(() => jest.requireActual('dayjs')(`2020-08-10 12:00:00`));
    // more mock
    return yourDay;
  })
}));

同时删除另一个模拟,因为它会替换:

jest.mock('dayjs', () => ({
  default: jest.requireActual('dayjs')(`2020-08-18 12:00:00`),
  extend: jest.fn(),
  // ...
}));

另一个解决方案,您可以更改并保持您的第一个模拟保持不变:

jest.mock('dayjs', () =>
  jest.fn((...args) => jest.requireActual('dayjs')(args.filter((arg) => arg).length > 0 ? args : '2020-08-12')),
);

您唯一要做的就是在您的tsconfig.json中启用选项esModuleInterop ,因为此选项会自动为您添加default function:

{
  "compilerOptions": {
    // ...
    "esModuleInterop": true,
  },
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM