我目前正在使用 react-testing-library 并且似乎无法弄清楚如何测试组件的 setState 。
在以下示例中,我尝试根据 API 中的数据测试加载的项目数是否正确。稍后将扩展它以测试诸如项目之间的交互之类的事情。
零件:
...
componentDidMount() {
this.getModules();
}
getModules () {
fetch('http://localhost:4000/api/query')
.then(res => res.json())
.then(res => this.setState({data : res.data}))
.catch(err => console.error(err))
}
...
render() {
return(
<div data-testid="list">
this.state.data.map((item) => {
return <Item key={item.id} data={item}/>
})
</div>
)
}
测试:
...
function renderWithRouter(
ui,
{route = '/', history = createMemoryHistory({initialEntries: [route]})} = {},) {
return {
...render(<Router history={history}>{ui}</Router>),
history,
}
}
...
test('<ListModule> check list items', () => {
const data = [ ... ]
//not sure what to do here, or after this
const { getByTestId } = renderWithRouter(<ListModule />)
...
//test the items loaded
expect(getByTestId('list').children.length).toBe(data.length)
//then will continue testing functionality
})
我知道这与开玩笑的模拟函数有关,但不明白如何使它们与设置状态或模拟 API 一起工作。
示例实现(工作!)
通过更多的实践和学习使组件可测试,我能够做到这一点。这是一个完整的示例供参考:https ://gist.github.com/alfonsomunozpomer/de992a9710724eb248be3842029801c8
const data = [...]
fetchMock.restore().getOnce('http://localhost:4000/api/query', JSON.stringify(data));
const { getByText } = renderWithRouter(<ListModule />)
const listItem = await waitForElement(() => getByText('Sample Test Data Title'))