gpt4 book ai didi

javascript - 无法从 "date-fns"模拟 startOfToday

转载 作者:行者123 更新时间:2023-12-02 22:12:30 26 4
gpt4 key购买 nike

我正在尝试模拟 js date-fns 模块中的函数。

我的测试顶部:

import { startOfToday } from "date-fns"

在测试期间,我尝试模拟:

startOfToday = jest.fn(() => 'Tues Dec 28 2019 00:00:00 GMT+0000')

当我运行测试时,这给了我错误:

"startOfToday" is read-only

最佳答案

您可以使用jest.mock(moduleName, factory, options)模拟 date-fns 模块的方法。

例如

index.js:

import { startOfToday } from 'date-fns';

export default function main() {
return startOfToday();
}

index.spec.js:

import main from './';
import { startOfToday } from 'date-fns';

jest.mock('date-fns', () => ({ startOfToday: jest.fn() }));

describe('59515767', () => {
afterEach(() => {
jest.resetAllMocks();
});
it('should pass', () => {
startOfToday.mockReturnValueOnce('Tues Dec 28 2019 00:00:00 GMT+0000');
const actual = main();
expect(actual).toBe('Tues Dec 28 2019 00:00:00 GMT+0000');
});
});

单元测试结果:

 PASS  src/stackoverflow/59515767/index.spec.js (10.095s)
59515767
✓ should pass (5ms)

----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
index.js | 100 | 100 | 100 | 100 | |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 12.081s

源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59515767

关于javascript - 无法从 "date-fns"模拟 startOfToday,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59515767/

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