Imagine I have a component that must be initialized once at the beginning of the application to pass on configuration. The module structure would look something like this:
MyComponent.js
let isInitialized;
const myComponent = {
init: function() {
isInitialized = true;
},
do: function() {
if (!isInitialized)
throw "error"
//DO THINGS
}
}
export default myComponent;
I want to write unit tests for it using jest. The test file would look something like this:
MyComponent.test.js
import myComponent from './MyComponent'
describe('MyComponent', () => {
describe('init', () => {
it('should not throw an exception when called', () => {
expect(() => myComponent.init()).not.toThrow();
});
})
describe('do', () => {
it('should throw an exception when not initialized', () => {
expect(() => myComponent.do()).toThrow();
});
})
})
However, when running the test, the second test fails because the module is already initialized and the exception is not thrown. I attempted using jest.resetModules() in beforeEach, but that did not resolve the issue.
Is there a solution to this problem, possibly by changing the module pattern or test case?