Imagine I have a legacy JS app with code like this:
var thing = new Thing();
function do_thing() {
// Logic to test here
}
// export module
This file also includes a number of important calculations I need to unit-test, without refactoring the whole thing.
I tried to test it with jest.
/**
* @jest-environment jsdom
*/
const mod = require('thing.js');
test('Test', () => {
mod.do_thing();
});
but get
ReferenceError: Thing is not defined
Even removing var thing
will cause errors if do_thing
has calls to functions defined in other files, as is usually the case in legacy projects.
ReferenceError: foo() is not defined
Any tips? Possible to mock out things using jest.fn
or jest.mock
similar without heavy refactoring of the app?
Solution using global.Thing
:
/**
* @jest-environment jsdom
*/
global.Thing = jest.fn();
const mod = require('thing.js');
test('Test', () => {
mod.do_thing();
});