[英]Write test to check local setState call with jest and react-testing-library
I am currently using react-testing-library and can't seem to work out how to test setState for components.我目前正在使用 react-testing-library 并且似乎无法弄清楚如何测试组件的 setState 。
In the following example, I am trying to test that the number of items loaded is correct based on the data from the API.在以下示例中,我尝试根据 API 中的数据测试加载的项目数是否正确。 Will later on expand this to test things like the interactions between of the items.稍后将扩展它以测试诸如项目之间的交互之类的事情。
Component:成分:
...
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>
)
}
Test:测试:
...
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
})
I understand this has to do with jest mock functions, but don't understand how to make them work with setting states, or with simulating an API.我知道这与玩笑模拟函数有关,但不明白如何使它们与设置状态或模拟 API 一起工作。
Sample Implementation (working!)示例实现(工作!)
With more practice and learning about making components testable, I was able to get this working.通过更多的练习和学习使组件可测试,我能够让它工作。 Here is a full example for reference: https://gist.github.com/alfonsomunozpomer/de992a9710724eb248be3842029801c8这是一个完整的示例供参考: 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'))
You should avoid testing setState
directly since that is an implementation detail of the component.您应该避免直接测试setState
,因为这是组件的实现细节。 You are on the right path to testing that the correct number of items are rendered.您正在测试是否呈现正确数量的项目。 You can mock the fetch
function by either replacing window.fetch
with a Jest mock function or using the fetch-mock library to handle the heavy lifting for you.您可以通过用Jest 模拟函数替换window.fetch
或使用fetch-mock库来为您处理繁重的工作来模拟fetch
函数。
// Note that this method does not build the full response object like status codes, headers, etc.
window.fetch = jest.fn(() => {
return Promise.resolve({
json: () => Promise.resolve(fakeData),
});
});
OR或者
import fetchMock from "fetch-mock";
fetchMock.get(url, fakeData);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.