简体   繁体   English

编写测试以使用 jest 和 react-testing-library 检查本地 setState 调用

[英]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.

相关问题 如何使用 React、Jest 和 React-testing-library 为带有令牌的 api 调用编写单元测试? - How can I write unit test for api call with token using React, Jest and React-testing-library? 使用React,Jest,React-Testing-Library测试失败的案例 - Test failing cases with React, Jest, React-Testing-Library 如何在使用jest和react-testing-library进行测试时设置组件的本地状态? - How to set component's local state while testing using jest and react-testing-library? Jest/react-testing-library:单击按钮未更新测试中的值 - Jest/react-testing-library: Clicking a button didn't update the value in test 如何使用 react-testing-library 和 jest 测试 function 组件中的 state - How to test state within function component with react-testing-library and jest 使用 Jest 和 react-testing-library 测试具有大量输入字段的表单的正确方法是什么? - What is the proper way to test a form with a lot of input fields using Jest and react-testing-library? 使用 react-testing-library 和 jest 测试是否调用了 prop 函数 - Testing if a prop function was called using react-testing-library and jest 使用 Jest + react-testing-library 测试异步 `componentDidMount()` - Testing async `componentDidMount()` with Jest + react-testing-library 如何在Jest和react-testing-library中使用react-hook - How to use react-hooks with Jest and react-testing-library Jest &amp; React &amp; Typescript &amp; React-Testing-Library 错误 - Jest & React & Typescript & React-Testing-Library error
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM