let's say I have a module that needs to be initialized once in the start of the app (to pass on configuration). module will look something like this :
MyModule.js
let isInitiazlied;
const myModule = {
init: function() {
isInitiazlied = true;
},
do: function() {
if (!isInitiazlied)
throw "error"
//DO THINGS
}
}
export default myModule;
I want to unittest it, using jest. test file looks something like this :
MyModule.test.js
import myModule from './MyModule'
describe('MyModule', () => {
describe('init', () => {
it('not throws exception when called', () => {
expect(() => myModule.init()).not.toThrow();
});
})
describe('do', () => {
it('throw when not init', () => {
expect(() => myModule.do()).toThrow();
});
})
})
when I run the test, the 2nd test fail, as the module already initialized so the exception is not thrown. I tried using jest.resetModules() in beforeEach, but that didn't work.
Is there a way to solve it (different module pattern/test case) ?
You have to re-import or re-require your module. Check the doc or this issue for more information:
https://github.com/facebook/jest/issues/3236
https://facebook.github.io/jest/docs/en/jest-object.html#jestresetmodules
describe('MyModule', () => {
beforeEach(() => {
jest.resetModules()
});
describe('init', () => {
const myModule = require('./MyModule');
it('not throws exception when called', () => {
expect(() => myModule.init()).not.toThrow();
});
})
describe('do', () => {
const myModule = require('./MyModule');
it('throw when not init', () => {
expect(() => myModule.do()).toThrow();
});
})
})
@ltamajs solution is great for require
but in the case you are using import
then you will receive the next error.
SyntaxError: /path/to/test/file.js: 'import' and 'export' may only appear at the top level
To solve this issue, you can use the babel-plugin-dynamic-import-node
plugin and then reset the modules. Overall, it looks like this:
describe('MyTests', () => {
let MyModule;
beforeEach(() => {
return import('../module/path').then(module => {
MyModule = module;
jest.resetModules();
});
});
test('should test my module', () => {
expect(MyModule.aMethod).not.toBeUndefined();
});
});
Source: https://github.com/facebook/jest/issues/3236#issuecomment-698271251
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With