R
R
Roman Yakimchuk2019-12-12 10:12:53
JavaScript
Roman Yakimchuk, 2019-12-12 10:12:53

How to restore a global method after a test in Jest?

Friends,
In Jest, if you do this: Date.now = jest.fn().mockReturnValue(1000);inside one test(...), then in all subsequent test(...)calls Date.now()it will return 1000, instead of the result of the original method Date.now().
There are four Jest options:

  1. clearMocks
  2. resetMocks
  3. resetModules
  4. restoreMocks

None of them brings the expected result. One only resets such methods, but instead of the native implementation, they begin to return undefined, i.e. there will be no more normal release date.
The question is, how to do it beautifully, without storing a reference to the original method in a variable, and rolling back the reference to the global module method after each test?
As far as I understand, the environment must be configured for each test, i.e. each test should be in the sandbox, but so far I haven’t found such options in Jest (extraGlobals looks like it, but not, as far as I understand).

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Roman Yakimchuk, 2019-12-12
@yakimchuk-ry

Found the answer purely by accident. Each test file is run in Jest in a separate VM context, so global variable mutation only works within the file, so this is NOT a problem, it does not affect tests outside the current file in any way.

P
Pavel Didenko, 2019-12-12
@Dasslier

Copy the Date to another variable and use that. Why overwrite a global method?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question