我想我找到了另一种使用 useContext
测试组件的方法。钩。我看过一些教程测试是否可以将值从父上下文提供程序成功传递给子组件,但没有找到有关子组件更新上下文值的教程。
我的解决方案是与提供者一起呈现根父组件,因为状态最终在根父组件中更改,然后传递给提供者,然后提供者将其传递给所有子组件。对?
测试似乎在应该通过的时候通过,而在不应该通过的时候却没有通过。
有人可以解释为什么这是或不是测试 useContext
的好方法吗?钩?
根父组件:
...
const App = () => {
const [state, setState] = useState("Some Text")
const changeText = () => {
setState("Some Other Text")
}
...
<h1> Basic Hook useContext</h1>
<Context.Provider value={{changeTextProp: changeText,
stateProp: state
}} >
<TestHookContext />
</Context.Provider>
)}
上下文对象:import React from 'react';
const Context = React.createContext()
export default Context
子组件:import React, { useContext } from 'react';
import Context from '../store/context';
const TestHookContext = () => {
const context = useContext(Context)
return (
<div>
<button onClick={context.changeTextProp}>
Change Text
</button>
<p>{context.stateProp}</p>
</div>
)
}
和测试:import React from 'react';
import ReactDOM from 'react-dom';
import TestHookContext from '../test_hook_context.js';
import {render, fireEvent, cleanup} from '@testing-library/react';
import App from '../../../App'
import Context from '../../store/context';
afterEach(cleanup)
it('Context is updated by child component', () => {
const { container, getByText } = render(<App>
<Context.Provider>
<TestHookContext />
</Context.Provider>
</App>);
console.log(container)
expect(getByText(/Some/i).textContent).toBe("Some Text")
fireEvent.click(getByText("Change Text"))
expect(getByText(/Some/i).textContent).toBe("Some Other Text")
})
最佳答案
您的示例/代码已死。 (不确定您是否需要安装包装 <App />
- 您应该直接包装在 Context Provider 中)。
对于你的问题:
The tests seem to pass when they should and not pass when they shouldnt. Can someone explain why this is or isnt a good way to test the useContext() hook.
使用
useContext()
时是一个很好的测试方法因为看起来您已经抽象出您的上下文,以便您的子(消费)组件及其测试都使用相同的上下文。当您使用相同的上下文提供程序时(如您在示例中所做的那样),我看不出您有任何理由模拟或模拟上下文提供程序正在做什么。React 测试库文档 point out那:
The more your tests resemble the way your software is used, the more confidence they can give you.
因此,以与设置组件相同的方式设置测试可以实现该目标。如果您在一个应用程序中有多个测试确实需要包装在同一个上下文中,this blog post有一个巧妙的解决方案来重用该逻辑。
关于reactjs - 使用 react-testing-library 测试 useContext(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56828017/