开玩笑未实现window.alert() [英] jest not implemented window.alert()
问题描述
我已经开玩笑地为我的api编写了测试.我在测试文件中添加了调用我的api的函数,如下所示:
i have written test for my api with jest . i added function that calls my api in test file as below:
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)
})
);
});
我的测试通过了,但是出现如下错误:
my test passes but i have an error as below:
错误:未实现:window.alert
Error: Not implemented: window.alert
如何解决这个问题?
推荐答案
默认测试环境表示Jest
是jsdom
提供的类似浏览器的环境.
The default test environment for Jest
is a browser-like environment provided by jsdom
.
jsdom
实现了实际浏览器将提供的大部分功能(包括全局window
对象),但并未实现所有功能.
jsdom
implements most of what an actual browser would provide (including the global window
object), but it doesn't implement everything.
专门针对这种情况,jsdom
不实现window.alert
,而是在调用它时抛出Error
,如在源代码
Specifically for this case, jsdom
does not implement window.alert
, and instead throws an Error
when it is called as can be seen in the source code here.
只要您知道代码为何启动alert
的原因,并且知道测试在Error
之外正常运行,则可以通过为window.alert
提供空实现来抑制Error
:
As long as you know why your code is launching the alert
and know that your test is working properly aside from the Error
then you can suppress the Error
by providing an empty implementation for window.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
});
这篇关于开玩笑未实现window.alert()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!