1

我目前正在使用 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'))
4

1 回答 1

5

您应该避免setState直接测试,因为这是组件的实现细节。您在测试是否呈现了正确数量的项目的正确路径。您可以fetch通过替换window.fetchJest 模拟函数或使用fetch-mock库为您处理繁重的工作来模拟该函数。

// 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),
  });
});

或者

import fetchMock from "fetch-mock";
fetchMock.get(url, fakeData);
于 2018-11-14T00:05:52.817 回答