[英]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.