gpt4 book ai didi

javascript - 模拟 DayJs 默认函数及其链式方法

转载 作者:行者123 更新时间:2023-12-05 00:35:32 24 4
gpt4 key购买 nike

我试图模拟 dayjs() 具有特定日期和时间的默认函数,并且还希望模拟其嵌套方法,即 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”是您要模拟的日期时。

关于javascript - 模拟 DayJs 默认函数及其链式方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63470910/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com