I have an IconFactory.ts which doesn’t have a default export:
export class Icon {
primary: string = "PR";
}
export interface IconFactory {
createAsync(entity: Entity): Promise<Icon>;
}
export class MyIconFactory implements IconFactory {
async createAsync(entity: Entity): Promise<Icon> {
const icon = new Icon();
//Some other logic
return icon;
}
}
And in my functionality code, Client.ts, I create an instance of MyIconFactory:
import {
MyIconFactory,
type Icon,
} from "IconFactory";
export async function createIcon(entity: Entity){
const iconFactory = new MyIconFactory();
await iconFactory.createAsync(entity);
}
I’m trying to write a unit test to test Client.createIcon(), by mocking IconFactory.createAsync() in Client.test.ts:
import {
Icon,
MyIconFactory,
} from "IconFactory";
import { createIcon } from "Client";
const mockIcon = new Icon();
const mockCreate = jest.fn().mockResolvedValue(mockIcon);
jest.mock("IconFactory", () => {
const originalModule = jest.requireActual(
"IconFactory"
);
return {
__esModule: true,
...originalModule,
MyIconFactory: jest.fn().mockImplementation(() => {
return { createAsync: mockCreate };
}),
};
});
it("should create markers when consignment addresses are overridden", async () => {
Entity entity = new Entity();
const result = createIcon(entity);
//...Assertions
});
But when this runs, it throws an error at await iconFactory.createAsync(entity);
: TypeError: iconFactory.createAsync is not a function.
Am I doing something wrong here?
Thanks in advance.
I’ve also tried
jest.spyOn(IconFactory.prototype).mockResolvedValue(mockIcon);
But that just didn’t mock at all. Client.createIcon() still used the original implementation in iconFactory.createAsync.
Chris Hong is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.