简体   繁体   English

带有 Redux 工具包的 React 测试库

[英]React Testing Library with Redux Toolkit

I am using Redux Toolkit approach by creating:我使用 Redux 工具包方法创建:

  1. slices with reducer and extra reducers带减速器和额外减速器的切片
  2. thunks with createAsyncThunk API thunks 与 createAsyncThunk API

I Want to understand what is the best way to test with React Testing Library the:我想了解什么是使用 React 测试库进行测试的最佳方法:

  1. slices with reducer and extra reducers带减速器和额外减速器的切片
  2. thunks with createAsyncThunk API thunks 与 createAsyncThunk API

A sample is given in the below gist: https://gist.github.com/subhranshudas/8021ec6d205a05680bc9e11f3ef7fb7d下面的要点给出了一个示例: https://gist.github.com/subhranshudas/8021ec6d205a05680bc9e11f3ef7fb7d

Any feedback is appreciated.任何反馈表示赞赏。

Note: I had asked the same question in Reddit and got the following reply: https://www.reddit.com/r/reduxjs/comments/hvwqc9/reduxtoolkit_unit_testing_strategy/ While I am clear with the "what" from the response, I am looking for a definitive " how " with React Testing Library.注意:我在 Reddit 上问过同样的问题并得到以下回复: https://www.reddit.com/r/reduxjs/comments/hvwqc9/reduxtoolkit_unit_testing_strategy/虽然我很清楚回复中的“内容”,但我我正在寻找 React 测试库的明确“方法”。

Apologies if it is an obvious question, but I am interested in checking out the definitive ways to do so in React Testing Library (since I am new to it)抱歉,如果这是一个明显的问题,但我有兴趣在 React Testing Library 中查看确定的方法(因为我是新手)

Thanks!谢谢!

The recommended practice has shifted from isolated unit testing to component/store integration tests.推荐的做法已经从孤立的单元测试转变为组件/存储集成测试。 Testing your components with your thunks/reducers verify the app behaves as expected the way a user would interact with it, while giving you coverage of your components and redux implementation.使用 thunks/reducers 测试您的组件,验证应用程序的行为是否符合用户与其交互的预期方式,同时让您覆盖组件和 redux 实现。 React Testing library is useful for testing components that are integrated with the store, and when your thunks make API requests, you can mock the responses using Mock Service Worker. React 测试库对于测试与商店集成的组件很有用,当您的 thunk 发出 API 请求时,您可以使用 Mock Service Worker 模拟响应。 If you only want to unit test the implementation details without components then you don't need React Testing Library.如果你只想对没有组件的实现细节进行单元测试,那么你不需要 React 测试库。

Eg testing a component containing a button that when clicked will fetch content from an API and then display the text in a heading:例如,测试一个包含按钮的组件,单击该按钮将从 API 获取内容,然后在标题中显示文本:

// import {render, screen} from '@testing-library/react'
// import userEvent from '@testing-library/user-event'
render( 
  <Provider store={store}>
    <MyComponent />
  </Provider>
)

const loadButton = screen.getByText('Load Content')
await userEvent.click(loadButton)

await screen.findByRole('heading') // waits for a heading before throwing
expect(screen.getByRole('heading')).toHaveTextContent('Mocked content')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM