reactjs - Jest 测试,sessionStorage 未定义

标签 reactjs jestjs

我正在尝试运行我的第一个 Jest 测试,但出现此错误

 FAIL  src\containers\__test__\AppContainer.spec.js
  ● Test suite failed to run

    ReferenceError: sessionStorage is not defined

我不确定我是否应该得到这个错误,因为我没有测试 sessionStorage,只是想测试根容器。

--更新--

import React from 'react'
import { shallow } from 'enzyme'
import AppContainer from '../AppContainer'

//Tried here also
global.sessionStorage = {
  data: {},
  setItem: (key, value) => {
    this.data[key] = value
  },
  getItem: (key) => this.data[key]
}
describe('AppContainer', () => {
  beforeEach(function () {
    global.sessionStorage = {
      data: {},
      setItem: (key, value) => {
        this.data[key] = value
      },
      getItem: (key) => this.data[key]
    }
  })

  it('should render self and subcomponents', () => {
    const enzymeWrapper = shallow(<AppContainer />)

    expect(enzymeWrapper.find('div').hasClass('grommetux-app')).toBe(true)
  })
})

--

ReferenceError: sessionStorage is not defined
  at Function.r.get (node_modules\oidc-client\lib\oidc-client.min.js:1:13009)
  at new e (node_modules\oidc-client\lib\oidc-client.min.js:74:15382)
  at new e (node_modules\oidc-client\lib\oidc-client.min.js:74:5255)
  at n (node_modules\redux-oidc\dist\redux-oidc.js:1:1853)
  **at Object.<anonymous> (src\utils\userManager.js:23:127)**
  at Object.<anonymous> (src\containers\AppContainer.js:9:46)
  at Object.<anonymous> (src\containers\__test__\AppContainer.spec.js:3:47)
  at process._tickCallback (internal\process\next_tick.js:103:7)

我正在通过库“使用”sessionStorage,oidc-clientjs ,所以我真的无法控制它。

错误来源的第23行是

import { createUserManager } from 'redux-oidc'
....
const userManager = createUserManager(config) (L23)

最佳答案

我正在使用 Create-react-app,所以我将它添加到 src/setupTests.js

const sessionStorageMock = {
  getItem: jest.fn(),
  setItem: jest.fn(),
  clear: jest.fn()
};
global.sessionStorage = sessionStorageMock;

关于reactjs - Jest 测试,sessionStorage 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40967727/

相关文章:

reactjs - 使用带有 Electron 编译错误的 TSX 文件

javascript - react : recursively render nested elements

javascript - 错误 : SyntaxError: Unexpected end of JSON input when using fetch()

ssl - 使用 playwright 代码生成忽略 SSL 错误

firebase - 是否可以模拟经过身份验证的 Firebase 用户,以便 Jest 运行完整测试,同时保留数据库规则?

javascript - 如何修复未捕获的类型错误 : Cannot read property 'name' of undefined

reactjs - 如何在 typescript 中使用 react-navigation 的 withNavigation?

unit-testing - 错误 : Action may not be undefined in async action testing in Redux app with nock and mock-store

react-native - 我如何 Jest 对 componentWillReceiveProps(nextProps) 进行单元测试?

javascript - 如何隔离和迭代 React 应用程序中的各个 React 组件