gpt4 book ai didi

reactjs - Jest 没有实现 window.alert()

转载 作者:行者123 更新时间:2023-12-03 13:02:38 25 4
gpt4 key购买 nike

我用 jest 为我的 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)
})
);
});

我的测试通过了,但出现以下错误:

Error: Not implemented: window.alert

如何解决这个问题?

最佳答案

default test environment for Jestjsdom 提供的类似浏览器的环境。

jsdom 实现了实际浏览器提供的大部分内容(包括全局 window 对象),但它并没有实现所有内容。

特别是对于这种情况,jsdom 没有实现 window.alert,而是在调用时抛出 Error(可以看出)在源代码中here .

<小时/>

只要您知道代码启动警报的原因,并且知道除了错误之外您的测试工作正常,那么您就可以抑制错误 通过为 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
});

关于reactjs - Jest 没有实现 window.alert(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55088482/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com