如何测试在窗口对象和打字稿中定义的函数
我正在尝试测试对全局窗口对象上定义的函数的调用。我已经查看了多个示例,但仍然无法运行一个简单的测试用例。
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.t.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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里的问题是您的进口订单。
当您从“ ./api”
导入{api}时,您运行
const verifier = window.verifier;
,当时是undefined <<
/代码>。如果您更改导入和间谍的顺序,则应按预期工作:
您还可以直接考虑使用
window.verifier
,使测试有点清洁:The problem here is your import order.
When you
import { Api } from "./api";
, you runconst verifier = window.Verifier;
, which, at the time, isundefined
.If you change the order of the imports and spies it should work as expected:
You could also think about using
window.Verifier
directly, making the tests a bit cleaner: