加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Windows > 正文

reactjs – jest没有实现window.alert()

发布时间:2020-12-14 02:18:23 所属栏目:Windows 来源:网络整理
导读:我用开玩笑为我的api写了测试.我添加了在测试文件中调用我的api的函数,如下所示: import AuthManager from "../Client/Modules/Auth/AuthManager"; 并使用如下: test("login api resolves true",() = { return expect(AuthManager.login("test","test")).r
我用开玩笑为我的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

如何解决这个问题呢 ?

解决方法

Jest的 default test environment是jsdom提供的类似浏览器的环境.

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

特别是对于这种情况,jsdom没有实现window.alert,而是在调用时抛出一个Error,如源代码here所示.

只要您知道为什么您的代码正在启动警报并且知道您的测试在Error之外正常工作,那么您可以通过为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",userId: expect.any(Number)
    })
  );  // SUCCESS
  window.alert = jsdomAlert;  // restore the jsdom alert
});

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读