I'm using ts-jest to test a JS/TS SDK/module. I'm running into a strange issue where a Jest test will run (no compile/import failures) but fail to correctly instantiate an object from the appropriate class.
test("Should build unit", () => {
const builder = new UnitBuilder("TEST_UNIT");
console.log(builder); // prints "{}"
const unit = builder
.addResource(...)
.build();
expect(unit.name).toBe("TEST_UNIT");
});
The test fails with: TypeError: builder.addResource is not a function
since the instantiated object is empty. Here's the class in question:
export class UnitBuilder {
constructor(templateId: string) {
this.payload = {
templateId,
parameters: [],
};
}
public addResource = (resource: CreateResourcePayload) => {
// do stuff
};
public build = () => {
// do stuff
};
public payload: CreateUnitPayload;
}
I'm assuming this has something to do with the jest
or ts-jest
transpilation, e.g. babel, but perhaps it's something to do with the jest configuration as well?
jest.config.ts
import type { Config } from "@jest/types";
const config: Config.InitialOptions = {
preset: "ts-jest",
testEnvironment: "node",
moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json"],
verbose: true,
automock: true,
testMatch: ["**/__tests/*.test.ts"],
roots: ["<rootDir>/src"],
transform: {
"^.+\\.(ts|tsx)$": "ts-jest",
},
};
export default config;
Removing automock: true
fixed the problem.