I am trying to write a test for a factory module. This factory module imports an object module that it then returns a new instance of given a specific string. The object that it imports imports more things, and one of the things it is importing imports another thing which imports another script that depends on some environment variables. That script runs, fails to find the environment variables it needs and kills the process before the test even gets started.
I don't find it should be necessary to import so many layers to test this specific factory. What's the right approach to solve this problem? Note that I'm very new to javascript/typescript, so any insight into the way package imports are supposed to work would be helpful.
jest.mock doesn't prevent the import statements on the underlying object from running.
//object-factory.ts
import {AnObject} from '../interfaces/an-object';
import VeryNiceObject from './very-nice-object';
export const VERY_NICE_STRING = 'this-string-is-very-nice'
export class ObjectFactory {
private readonly str: string;
constructor(str: string) {
this.str = str;
}
public build(): AnObject {
switch (this.str) {
case VERY_NICE_STRING:
return new VeryNiceObject();
default:
throw new Error(`Unknown string ${this.str}`);
}
}
}
I am trying to isolate this module under test. My test looks like this -
jest.mock("../very-nice-object")
import {AnObject} from "../../interfaces/an-object";
import {ObjectFactory, VERY_NICE_STRING} from "../object-factory"; //FAILS HERE
import VeryNiceObject from "../very-nice-object";
describe('object-factory', () => {
test("build returns VeryNiceObject", () => {
const factory = new ObjectFactory(VERY_NICE_STRING)
const objectResult = factory.build()
expect(objectResult instanceof VeryNiceObject)
})
});
I have also tried running with automock on at the top of the file and it fails for a different reason.
jest.autoMockOn()
...rest of test
● Test suite failed to run
TypeError: Expected a string
at escapeStringRegexp (node_modules/colors/lib/colors.js:80:11)
at node_modules/colors/lib/colors.js:101:18
at Array.forEach (<anonymous>)
at node_modules/colors/lib/colors.js:99:27
at Object.<anonymous> (node_modules/colors/lib/colors.js:109:3)