繁体   English   中英

使用 mount 和 React 的上下文进行玩笑测试 API

[英]Jest testing with mount and React's context API

我正在尝试使用 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
})

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

Provider 接受 value 属性而不是 context 属性。 https://reactjs.org/docs/context.html#contextprovider

AppContext.Provider 值={{ state: { 用户: SUPER_USER } }}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM