Search code examples
javascriptjestjsdate-fns

Unable to mock startOfToday from "date-fns"


I'm trying to mock a function from js date-fns module.

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

Solution

  • You can use jest.mock(moduleName, factory, options) method to mock date-fns module.

    E.g.

    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');
      });
    });
    

    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