jestjs / jest

Delightful JavaScript Testing.
https://jestjs.io
MIT License
44.08k stars 6.45k forks source link

Documentation: Guide for mocking ES6 modules (different from ES6 classes) #8544

Closed sargalias closed 5 years ago

sargalias commented 5 years ago

🚀 Feature Proposal

A guide on using ES6 modules with Jest. The guide would probably go above "ES6 Class Mocks" on the sidebar.

It would explain the __esModule: true property when using jest.mock and provide examples for using it and not using it.

It would also explain that ES6 modules are non-writable unlike CommonJS. To create a different mock in a specific test you have to:

  1. Reset modules with jest.resetModules().
  2. Create the new mock with jest.doMock inside the specific test.
  3. Dynamically re-import the module with import().

Motivation

I haven't found any information on the Jest website about using the __esModules: true property. Without that information users would not be able to properly use ES6 module mocks in their tests without using manual mocks.

I also haven't found information on the Jest website mentioning how having a different mock for an ES6 module requires re-importing the module dynamically.

As a result I've gotten very stuck in the past on how to properly mock ES6 modules. I think this information would help a lot of users.

Please let me know your thoughts. If interested I can make a PR.

jeysal commented 5 years ago

Hey @sargalias, thanks for your interest in improving the documentation :) doMock, resetModules and dynamic imports just to make mocking work are things that I'd like the documentation not to encourage to avoid fragile/complicated test setups - usually there are better ways of solving these cases, maybe the docs need to get better at offering alternatives to doMock etc. instead?

sargalias commented 5 years ago

Hey @jeysal, it's a pleasure. Ah that's fair enough. To be honest I think manual mocks are sufficient for most cases. I was thinking more from a point of view of having that information available.

I understand the sentiment. In that case I'm happy to close the issue.

jeysal commented 5 years ago

Super happy about improvements to etc. the doMock API docs, just for guides I think we should avoid these things / show people how to avoid them :)

github-actions[bot] commented 3 years ago

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs. Please note this issue tracker is not a help forum. We recommend using StackOverflow or our discord channel for questions.