【发布时间】:2019-11-11 15:48:15
【问题描述】:
我想我找到了另一种使用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")
})
【问题讨论】:
标签: reactjs testing jestjs react-hooks