我开玩笑地为我的api编写了测试。我添加了在测试文件中调用我的api的函数,如下所示:
import AuthManager from "../Client/Modules/Auth/AuthManager";
并如下使用:
test("login api resolves true", () => { return expect(AuthManager.login("test", "test")).resolves.toMatchObject( expect.objectContaining({ accessToken: expect.any(String), email: expect.any(String), expiresIn: expect.any(Number), refreshToken: expect.any(String), userFullName: expect.any(String), userId: expect.any(Number) }) ); });
我的测试通过了,但是出现以下错误:
错误:未实现:window.alert
如何解决这个问题呢 ?
在默认的测试环境为Jest是一个类似浏览器所提供的环境jsdom。
Jest
jsdom
jsdom实现了实际浏览器将提供的大部分功能(包括全局window对象),但并未实现所有功能。
window
专门为这种情况下,jsdom没有实现window.alert,而是抛出Error时,它被称为可以在源代码中可以看出这里。
window.alert
Error
只要您知道代码为什么要启动,alert并且知道测试除了之外Error还可以正常运行,那么您可以Error通过为空提供以下实现来抑制window.alert:
alert
test("login api resolves true", () => { const jsdomAlert = window.alert; // remember the jsdom alert window.alert = () => {}; // provide an empty implementation for window.alert return expect(AuthManager.login("test", "test")).resolves.toMatchObject( expect.objectContaining({ accessToken: expect.any(String), email: expect.any(String), expiresIn: expect.any(Number), refreshToken: expect.any(String), userFullName: expect.any(String), userId: expect.any(Number) }) ); // SUCCESS window.alert = jsdomAlert; // restore the jsdom alert });