[英]An update to Provider inside a test was not wrapped in act(…) with Jest + React Testing Library
[英]Testing a React Provider wrapped component with useReducer using Jest
我一直在努力測試包裝在提供程序中的組件,該組件的值來自組件useReducer
reducer。
目前,我正在將reducer稱為<NavUpdateDispatchContext.Provider value={useNavDispatch()}>
問題是這不起作用,因為我無法在組件外部使用useReducer
?
有誰知道解決這個問題的方法嗎?
這是codesandbox: https ://codesandbox.io/s/stupefied-firefly-3gqyz
該測試位於src/SignOut/__tests__/SignOut-test.tsx
我得到的錯誤是:
不變違規:無效的掛接調用。 掛鈎只能在功能組件的主體內部調用。
抱歉,沙盒無法呈現,因為它需要firebase,但我認為代碼可能夠用了?
非常感謝
要保存訪問代碼和框,請執行以下操作:
//Current test: /src/SignOut/__tests__/SignOut-test.tsx
test('renders a Sign Out button', () => {
render(
<NavUpdateDispatchContext.Provider value={useNavDispatch()}>
<NavStatusContext.Provider value={{ navIsOpen: false }}>
<SignOut />
</NavStatusContext.Provider>
</NavUpdateDispatchContext.Provider>,
)
})
// Sign out: /src/SignOut/index.tsx
interface P {
firebase: firebase.app.App
}
const SignOut = ({ firebase }: P) => {
const dispatch = useNavDispatch()
return (
<LinkButton
onClick={() => {
firebase
.auth()
.signOut()
.then(() => dispatch({ type: 'close' }))
}}
>
SignOut
</LinkButton>
)
}
// Nav Reducer in /src/Header/index.tsx
const navReducer = (state: State, action: Action) => {
switch (action.type) {
case 'open': {
return { navIsOpen: true }
}
case 'close': {
return { navIsOpen: false }
}
default: {
throw new Error(`Unhandled action type in navReducer: ${action!.type}`)
}
}
}
我建議您在測試中呈現Header
,這樣就不必模擬上下文。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.