[英]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");
}),
})),
}));
兩者都不起作用。 有人有建議嗎?
假設您正在嘗試創建一致的 output 而忽略給定的日期參數,您可以像這樣創建節點模塊模擬:
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"`);
});
});
MockDate 非常適合這個,不需要強烈的 mocking 代碼。
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();
我正在使用插件 customParseFormat,我只是這樣模擬:
jest.mock('dayjs/plugin/customParseFormat', () => ({
default: jest.requireActual('dayjs/plugin/customParseFormat'),
}));
這個對我有用。
當我需要進行更新時,我已經用一種簡單的方式解決了 expect.any(Date) 的問題。 我記錄了實際日期,並在測試中使用了 expect.any(Date) 來查看 updatedAt 字段中的查詢是否傳遞了任何日期。
expect(prisma.transaction.update).toBeCalledWith({
where: {
id: 'any_id'
},
data: {
error: 'Error message here',
tries: 1,
updatedAt: expect.any(Date)
}
});
我發現的最佳解決方案是使用 jest fake timers,請參閱文檔。
describe('myDayjsFunction', () => {
it('returns my value', () => {
const param = 3
jest.useFakeTimers().setSystemTime(new Date('2023-01-10'))
const actual = myDayjsFunction(param)
const expected = 5
expect(actual).toEqual(5)
jest.useRealTimers()
})
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.