Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

how to mock moment() in jest? #5962

Open
alirezahmz opened this issue Dec 21, 2021 · 2 comments
Open

how to mock moment() in jest? #5962

alirezahmz opened this issue Dec 21, 2021 · 2 comments

Comments

@alirezahmz
Copy link

i'm using moment-jalaali": "^0.9.4",
i get this error when i try to run test : moment is not a function
and after google it, i found this code:
jest.mock('moment', () => ({
format: () => '2018–01–30T12:34:56+00:00'
}));
and run again
get this error: TypeError: moment.localeData is not a function

@DiscoNova
Copy link

When You want to mock a package such as Moment in Jest (or any other test library for that matter), You need to implement mock for all the methods the package provides (or more precisely "for all the methods the package provides that Your code uses").

In this particular case, Your code uses moment.localeData() in addition to moment.format(), so ... Your mock should also implement that method.

Basically, Your mock should look something like....

jest.mock('moment', () => ({
    format: () => '2018-01-30T12:34:56+00:00',
    localeData: () => /* should return whatever your test expects it to ... YMMV */
}));

Sometimes mocking packages is a good approach in testing. Sometimes You want to actually use the real package (but preheat it with known values during testing). Your mileage may vary. Hope this helps.

@angelzabala
Copy link

angelzabala commented Jul 11, 2022

You could use jest.requireActual so you woldn't have to mock the behavior of something that you are probably going to expect to work the same us usual.
You could also set jest.setSystemTime to add consistency to tests, doing so could help you with things like testing calendars or similar stuff

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants