Jest: Automatic restore for spyOn

Created on 22 Feb 2017  路  9Comments  路  Source: facebook/jest

As already mentioned in #1749, could spyOn have automatic restore as jasmine has?

It would help to isolate spies for given test, as its simple to forget to call the restore at the end of the test (and can affect the other tests which is always difficult to track down).

And also there is no guarantee that the restore will get called, because test might fail in some expect, which stops the execution of the test and prevents calling the restore, which is usually called at the end of the test function.

Feature Request Discussion

Most helpful comment

Would you also accept a PR to the docs to clear up the difference between clear/reset mocks? We've got very confused between clearMocks and resetMocks. My understanding is:

  • clearMocks resets all the mock's history but leaves the fake implementation
  • resetMocks resets any fake implementations but doesn't restore the original behaviour

Is that correct? If that is correct, it feels like restoreMocks as a way to put back the original implementation would fit nicely as a 3rd option. If not I'd love to see an example of how you do this at Facebook to avoid this being an issue :)

All 9 comments

Similar issue was discussed here: https://github.com/facebook/jest/issues/2965.

Would you also accept a PR to the docs to clear up the difference between clear/reset mocks? We've got very confused between clearMocks and resetMocks. My understanding is:

  • clearMocks resets all the mock's history but leaves the fake implementation
  • resetMocks resets any fake implementations but doesn't restore the original behaviour

Is that correct? If that is correct, it feels like restoreMocks as a way to put back the original implementation would fit nicely as a 3rd option. If not I'd love to see an example of how you do this at Facebook to avoid this being an issue :)

@jackfranklin docs PRs are always welcome!

@thymikee OK, I'll get one in ;) Are my definitions of clear/reset mocks correct in the comment above?

I don't like the naming either. The definitions seems ok 馃憤

@thymikee given we have mockFn.mockRestore(), would you be open to a PR that adds restoreMocks: true as a config that would call restoreAllMocks which in turn would call mockRestore on each known mock?

Feel free to open a separate issue just for that, so we can discuss.

Looks like this feature's been in the codebase since #3580 was merged last year. May be worth closing.

@geoffreyyip yup, thanks, docs are here

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ianp picture ianp  路  3Comments

StephanBijzitter picture StephanBijzitter  路  3Comments

stephenlautier picture stephenlautier  路  3Comments

withinboredom picture withinboredom  路  3Comments

samzhang111 picture samzhang111  路  3Comments