Allow passing variable arguments to jest.resetModules to specify which modules should be reset.
I have several files that contain local state which I would like to reset between tests. However, I do not want to reset and re-import all of the dependencies in the test file because this seems 1) unnecessary and 2) error prone and easy to forget.
Here is a somewhat simplified example:
jest.mock('logger');
let logger;
let myModule;
beforeEach(() => {
jest.clearAllMocks()
.resetModules();
logger = require('logger');
myModule = require('../myModule');
});
jest.mock('logger');
const logger = require('logger');
let myModule;
beforeEach(() => {
jest.clearAllMocks()
.resetModules('../myModule'); // pass in the desired file to be reset
/** only reload the module that I want to reset **/
myModule = require('../myModule');
});
It would remove cruft, add specificity, and give finer-grained control.
How about filling issue template?
Hi, thanks for reporting!
This seems like an interesting use case. Here is the code for resetModules. https://github.com/facebook/jest/blob/master/packages/jest-runtime/src/index.js#L421-L441
My initial impression is that if we want to support this, it would not be that hard, except for a couple of things:
this._environment.global and envGlobal.mockClearTimers when "module path" arguments are passed?Given that resetModules has remained untouched for 2+ years, https://github.com/facebook/jest/blame/master/packages/jest-runtime/src/index.js#L421-L441, I guess @cpojer might have better insights.
@benmj I understand the use case for just resetting one module rather than all of them. I'm trying to reproduce and better understand the implications of:
I also need to re-require other modules that do not contain local state.
Do you mind providing an example?
Is this similar to what you are mentioning?
import x from './withLocalState';
import y from './stateless';
beforeEach(() => {
jest.resetModules();
});
it('some test', () => {
// In here `y` is still the correct object right?
})
@benmj our Feature Proposal template should be followed for all feature proposals. It has sections for questions that will come up like the ones @rogeliog brings up
I think this is a great proposal, so let us know when you update the description to follow that template and we'll reopen
Would #6174 fulfill the use case?
Thanks for the comments. I've updated to follow the template.
Thanks for the update 馃憤
I agree with @SimenB about @gaearon's proposal(#6174). Even though it uses a different abstraction, would it be correct to say that both proposals are trying to solve a same or a similar problem?
Closing in favor of #6174