I have been struggling to test a function call that is defined on the global window object. Despite reviewing various examples, I am still unable to successfully execute a simple test case.
Api.ts
import "./global.d";
const verifier = window.Verifier;
export class Api {
constructor(private readonly id: string) {}
public fetchData() {
return new Promise<object>((resolve, reject) => {
verifier.request({
request: {
id: this.id
},
onSuccess: (data: object) => {
resolve(data);
},
onFailure: () => {
reject("Error!");
}
});
});
}
}
Api.test.ts
import { Api } from "./Api";
let windowSpy: any;
describe("Test Apis", () => {
beforeEach(() => {
windowSpy = jest.spyOn(window, "window", "get");
});
afterEach(() => {
windowSpy.mockRestore();
});
it("should call the function", () => {
const mockedReplace = jest.fn();
windowSpy.mockImplementation(() => ({
Verifier: {
request: mockedReplace
}
}));
const api = new Api("123");
api.fetchData();
expect(mockedReplace).toHaveBeenCalled();
});
});
global.d.ts
import { Verifier } from "./verifier";
declare global {
interface Window {
Verifier: Verifier;
}
}
verifier.d.ts
type RequestPayload = {
request: {
id: string;
};
onSuccess: (data: object) => void;
onFailure: () => void;
};
type verifyCode = number;
export interface Verifier {
request: (requestPayload: RequestPayload) => verifyCode;
}
In order to provide further clarity, I have created a codesandbox example which can be accessed through the following link: https://codesandbox.io/s/cranky-mccarthy-2jj622?file=/src/verifier.d.ts