开玩笑没有实现 window.alert() [英] jest not implemented window.alert()
问题描述
我开玩笑地为我的 API 编写了一个测试.我在测试文件中添加了一个调用我的 API 的函数,如下所示:
I have written a test for my API with jest. I added a function that calls my API in the 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
我该如何解决这个问题?
How do I solve this problem?
推荐答案
默认测试环境 for 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
之外您的测试工作正常,那么您就可以抑制 Error
通过为 window.alert
提供一个空的实现:
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屋!