[英]How can I test a context in react with Jest/react-testing-library
I am trying to test a component that uses the context, but I couldn't pass a mock value to the context in my tests, here is my setup.我正在尝试测试使用上下文的组件,但我无法在测试中将模拟值传递给上下文,这是我的设置。
This is my context component:这是我的上下文组件:
AuthContext:授权上下文:
export const AuthContext = React.createContext([])
export const AuthProvider = ({children}) => {
const [AllUserInfo, setAllUserInfo] = useState(null)
return <AuthContext.Provider value={{AllUserInfo, setAllUserInfo}}>
{children}
</AuthContext.Provider>
}
export const useAuthContext = () => React.useContext(AuthContext)
I wrapped the App component in index.js with AuthProvider我使用 AuthProvider 将 App 组件包装在 index.js 中
index.js: index.js:
<AuthProvider>
<App/>
</AuthProvider>
Now in another component get the context like this:现在在另一个组件中获取如下上下文:
ContactUs:联系我们:
const ContactUs = () => {
const {AllUserInfo} = useAuthContext()
console.log(AllUserInfo)
The code is very long so I just copied the important part like how I call my context in my components and it works in my app.代码很长,所以我只是复制了重要的部分,比如我如何在组件中调用上下文,它在我的应用程序中工作。 When a user is logged in all of the information is then stored in the context that happens in another component.当用户登录时,所有信息都会存储在另一个组件中发生的上下文中。
Here is what I tried in my tests:这是我在测试中尝试的:
const {queryByTestId} = render(
<AuthProvider.Provider value={userMock}>
<ContactUs />
</AuthProvider.Provider>
);
userMock is just an object that contains mock user information for the test. userMock 只是一个包含用于测试的模拟用户信息的 object。 I may be doing this test completely wrong.我可能做这个测试完全错误。 I am open to any solutions, it doesn't have to be similar to the test I wrote.我对任何解决方案持开放态度,它不必与我编写的测试相似。
the solution was very simple, here what worked for me:解决方案非常简单,这对我有用:
const {queryByTestId} = render(
<AuthContext.Provider value={{AllUserInfo: userMock}}>
<ContactUs/>
</AuthContext.Provider>
)
I map the value of the context I want to change to the mock object I created in my test我 map 我想更改为我在测试中创建的模拟 object 的上下文的值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.