【问题标题】:jsdom: Cannot read property '_location' of nulljsdom:无法读取 null 的属性“_location”
【发布时间】:2017-08-28 15:31:20
【问题描述】:

当我通过 jest 测试史诗时,我的测试失败了。

Test Failed
/.../node_modules/jsdom/lib/jsdom/browser/Window.js:148

return idlUtils.wrapperForImpl(idlUtils.implForWrapper(window._document)._location);

TypeError: Cannot read property '_location' of null
    at Window.get location [as location] (/.../node_modules/jsdom/lib/jsdom/browser/Window.js:148:79)
    at Timeout.callback [as _onTimeout] (/.../node_modules/jsdom/lib/jsdom/browser/Window.js:525:40)
    at ontimeout (timers.js:380:14)
    at tryOnTimeout (timers.js:244:5)
    at Timer.listOnTimeout (timers.js:214:5)

这是我的一些测试。我在 fetchCategoriesEpic 中使用了 fetch() 和 promise。

it('test epic', () => {
    ...
    const action$ = ActionsObservable.of({ type: FETCH_CATEGORIES })

    fetchCategoriesEpic(action$)
      .toArray() // collects everything in an array until our epic completes
      .subscribe((actions) => {
        expect(actions).toEqual([
          { type: FETCH_CATEGORIES },
          { type: FETCH_CATEGORIES_SUCCESS, payload: List(payload.data).map((category) => new Category(category)) }
        ])
      })
    ...
}

我该如何解决这个问题?

【问题讨论】:

    标签: reactjs unit-testing jestjs jsdom


    【解决方案1】:

    看来这个问题真的只与 jsdom 相关,与 redux-observable 无关, 所以你可能想改变你的标题、描述、标签。您可能希望在测试中包含 jsdom 的任何配置/用法以及您使用的节点版本。

    Others have reported 过去有类似问题,但我无法通过快速 Google 搜索找到明确的解决方案。我的直觉会告诉我你的配置有点不对劲,它没有意识到它应该为你创建一个假的位置对象。

    【讨论】:

      【解决方案2】:

      我在未定义 document 的环境中进行测试时尝试使用 document.documentElement 时遇到了这个问题。

      我在应用程序代码的那部分添加了一个条件,之后我的测试运行良好。

      确保您的应用程序代码而不是您的测试代码正在尝试访问仅存在于您的测试环境中的元素。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-10-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-29
        • 2016-11-24
        相关资源
        最近更新 更多