简体   繁体   English

无法从“date-fns”模拟 startOfToday

[英]Unable to mock startOfToday from “date-fns”

I'm trying to mock a function from js date-fns module.我正在尝试从 js date-fns模块模拟一个函数。

Top of my test:我的测试的顶部:

import { startOfToday } from "date-fns"

During my test I try to mock:在我的测试中,我尝试模拟:

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

Which gives me the error when I run the tests:当我运行测试时,这给了我错误:

"startOfToday" is read-only

You can use jest.mock(moduleName, factory, options) method to mock date-fns module.您可以使用jest.mock(moduleName, factory, options)方法来模拟date-fns模块。

Eg例如

index.js : index.js

import { startOfToday } from 'date-fns';

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

index.spec.js : 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');
  });
});

Unit test result:单元测试结果:

 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

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

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

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