【问题标题】:Jest testing with mount and React's context API使用 mount 和 React 的上下文 API 进行玩笑测试
【发布时间】:2019-09-23 16:09:38
【问题描述】:

我正在尝试使用 mount 来测试我的上下文 API 实现,但我收到了一个错误

TypeError:无法读取未定义的属性“状态”

我尝试了各种技术在测试期间将上下文数据传递给组件,但到目前为止都没有成功。

ApplicationContext.js

import React from 'react'

const AppContext = React.createContext()
export default AppContext

MyComponent.js 文件

render () {
  return (
    <AppContext.Consumer>
      {context => (
        { context.state.user === SUPER_USER
          ? <Dashboard></Dashboard>
          : <Info></Info>
      )}
    </AppContext.Consumer>
  )
}

我尝试过的方法

//version 1
const wrapper = mount(<AppContext.Provider context={{ state: { user: SUPER_USER } }}><ActivityDisplay {...props} /></AppContext.Provider>)
  instance = wrapper.instance()
})

//version 2
wrapper = mount(<HomePage {...props} />, {
  context: { state: { user: SUPER_USER } },
})

//version 3
wrapper = mount(<HomePage {...props} />, {
  AppContext: {
    Consumer: { user: SUPER_USER }
  }
})

afterAll(() => {
  wrapper.unmount()
})

it('should display dashboard when user is SUPER_USER', () => {
  //do my assertions here
})

当我使用上述测试代码调试应用程序时,上下文始终未定义

【问题讨论】:

    标签: reactjs unit-testing jestjs


    【解决方案1】:

    Provider 接受一个值属性而不是上下文属性。 https://reactjs.org/docs/context.html#contextprovider

    AppContext.Provider value={{ state: { user: SUPER_USER } }}

    【讨论】:

      猜你喜欢
      • 2022-06-15
      • 2017-11-29
      • 2020-03-02
      • 2020-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-13
      • 2015-02-06
      相关资源
      最近更新 更多