【问题标题】:"ReferenceError: indexedDB is not defined" when testing React component with Jest使用 Jest 测试 React 组件时出现“ReferenceError: indexedDB is not defined”
【发布时间】:2022-01-31 01:06:46
【问题描述】:

我使用 Create React App 创建了一个 React App,它使用 IndexedDB。

当我尝试运行测试时出现此错误:

[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "ReferenceError: indexedDB is not defined".] {
  code: 'ERR_UNHANDLED_REJECTION'
}

我了解测试套件是在没有 IndexedDB 的无头浏览器中运行的。

我该如何处理这种情况?

【问题讨论】:

    标签: javascript reactjs jestjs react-testing-library indexeddb


    【解决方案1】:

    实际上,Jest 是用来模拟内存中的 DOM,而不是在实际的无头浏览器中。因此,您必须模拟这种 API 才能使您的测试通过。

    我找到了一篇解释how to mock indexedDB in Jest的文章

    【讨论】:

    • 部分使用它。如果我将它添加到 App.test.js 并且我的嵌套组件是由于某种原因使用 IndexedDB 的组件,它仍然会失败。
    猜你喜欢
    • 2018-06-04
    • 2019-12-02
    • 2021-03-19
    • 1970-01-01
    • 2021-03-29
    • 2020-08-14
    • 2020-06-14
    • 1970-01-01
    • 2022-07-10
    相关资源
    最近更新 更多