Kiểm thử ứng dụng Redux đã kết nối bằng Redux Testing Library

Kiểm thử ứng dụng Redux đã kết nối bằng Redux Testing Library

Khám phá cách kiểm thử tích hợp cho các ứng dụng Redux đã kết nối bằng Redux Testing Library, đảm bảo chất lượng, dễ bảo trì và phát hiện lỗi sớm trong quá trình phát triển.
23/02/2024
2,030 Lượt xem

Giới thiệu về Redux Testing Library

Redux là một thư viện quản lý trạng thái phổ biến cho các ứng dụng JavaScript. Nó cung cấp một cấu trúc dữ liệu trung tâm, gọi là store, để lưu trữ trạng thái của ứng dụng. Các thành phần React có thể kết nối với store này thông qua React-Redux, một thư viện liên kết Redux với React.

Redux Testing Library là một tập hợp các công cụ hữu ích để kiểm thử các ứng dụng Redux đã kết nối. Nó được xây dựng trên nền tảng của React Testing Library, một thư viện kiểm thử được thiết kế để kiểm tra các thành phần React một cách đơn giản và hiệu quả.

Thiết lập Redux Testing Library

Để bắt đầu với Redux Testing Library, hãy cài đặt các gói phụ thuộc cần thiết:

npm install --save-dev @testing-library/react @testing-library/jest-dom @redux-tools/testing-library

Tiếp theo, hãy tạo một tệp cấu hình mới cho Redux Testing Library, ví dụ như setupTests.js, và thêm đoạn mã sau đây:

import '@testing-library/jest-dom/extend-expect'; import { configureStore } from '@reduxjs/toolkit'; import { render } from '@testing-library/react'; import { Provider } from 'react-redux'; const configureTestStore = (initialState) => { const store = configureStore({ reducer: (state = initialState, action) => state }); const originalDispatch = store.dispatch; store.dispatch = jest.fn(originalDispatch); return store; }; const renderWithRedux = (component, initialState) => { const store = configureTestStore(initialState); return { ...render({component}), store, }; }; global.renderWithRedux = renderWithRedux; 

Trong đoạn mã này, chúng ta đã tạo một hàm configureTestStore để khởi tạo một Redux store mới với một reducer đơn giản trả về trạng thái ban đầu. Hàm renderWithRedux sau đó sử dụng store này để render các thành phần được bao bọc bởi Provider của React-Redux, cho phép chúng truy cập vào store và kết nối với Redux.

Viết các kiểm thử tích hợp với Redux Testing Library

Bây giờ chúng ta đã sẵn sàng để viết các kiểm thử tích hợp cho các thành phần Redux đã kết nối. Hãy xem xét một ví dụ đơn giản về một thành phần Counter kết nối với Redux, có chức năng tăng và giảm một số đếm:

import React from 'react'; import { useSelector, useDispatch } from 'react-redux'; import { increment, decrement } from './counterSlice'; const Counter = () => { const count = useSelector((state) => state.counter.value); const dispatch = useDispatch(); const handleIncrement = () => { dispatch(increment()); }; const handleDecrement = () => { dispatch(decrement()); }; return ( 

Counter

Current count: {count}

); }; export default Counter;

Để kiểm thử thành phần này, chúng ta có thể tạo một tệp kiểm thử mới, chẳng hạn như Counter.test.js, và viết các trường hợp kiểm thử như sau:

import React from 'react'; import { fireEvent } from '@testing-library/react'; import Counter from './Counter'; describe('Counter component', () => { it('should increment count when the Increment button is clicked', () => { const { getByText, getByRole } = renderWithRedux(, { counter: { value: 0 } }); const incrementButton = getByRole('button', { name: 'Increment' }); fireEvent.click(incrementButton); const count = getByText('Current count: 1'); expect(count).toBeInTheDocument(); }); it('should decrement count when the Decrement button is clicked', () => { const { getByText, getByRole } = renderWithRedux(, { counter: { value: 5 } }); const decrementButton = getByRole('button', { name: 'Decrement' }); fireEvent.click(decrementButton); const count = getByText('Current count: 4'); expect(count).toBeInTheDocument(); }); }); 

Trong đoạn mã trên, chúng ta sử dụng hàm renderWithRedux đã được định nghĩa trước đó để render thành phần Counter với trạng thái ban đầu khác nhau. Sau đó, chúng ta sử dụng các phương thức như getByTextgetByRole từ React Testing Library để truy cập các phần tử trong DOM và gửi sự kiện click bằng cách sử dụng fireEvent.click. Cuối cùng, chúng ta kiểm tra xem số đếm hiện tại có phù hợp với giá trị mong đợi hay không.

Bằng cách sử dụng Redux Testing Library, chúng ta có thể viết các kiểm thử tích hợp mạnh mẽ và dễ bảo trì cho các ứng dụng Redux đã kết nối. Thư viện này cung cấp các công cụ hữu ích để tương tác với Redux store và kiểm tra rằng các hành động và reducer đang hoạt động đúng cách.

Lợi ích của kiểm thử tích hợp với Redux Testing Library

Việc kiểm thử tích hợp với Redux Testing Library mang lại nhiều lợi ích cho quá trình phát triển ứng dụng React và Redux:

Đảm bảo chất lượng

Các kiểm thử tích hợp giúp bạn xác minh rằng các thành phần đã kết nối của ứng dụng đang hoạt động đúng cách trong môi trường tương tác với Redux store. Điều này đảm bảo rằng ứng dụng của bạn có chất lượng cao và ít gặp lỗi hơn.

Dễ bảo trì

Khi sử dụng Redux Testing Library, các kiểm thử của bạn sẽ dễ đọc và dễ bảo trì hơn. Các công cụ và API được cung cấp bởi thư viện này giúp viết các kiểm thử giống như cách người dùng sẽ tương tác với ứng dụng, giúp đoạn mã kiểm thử trở nên gần gũi và dễ hiểu hơn.

Phát hiện lỗi sớm

Các kiểm thử tích hợp cho phép bạn phát hiện các vấn đề trong ứng dụng của mình ngay từ đầu quá trình phát triển. Bạn có thể dễ dàng xác định và sửa chữa các lỗi trước khi chúng trở thành vấn đề lớn hơn, giúp tiết kiệm thời gian và chi phí.

Tăng tính tin cậy

Khi có một bộ kiểm thử tích hợp toàn diện, bạn có thể tự tin hơn khi thực hiện các thay đổi trong ứng dụng của mình. Các kiểm thử sẽ đảm bảo rằng các thay đổi đó không gây ra hậu quả bất ngờ và ảnh hưởng đến các tính năng hiện có.

Kết luận

Redux Testing Library là một công cụ mạnh mẽ để kiểm thử các ứng dụng Redux đã kết nối. Bằng cách sử dụng thư viện này, bạn có thể tạo ra các kiểm thử tích hợp dễ bảo trì, đảm bảo chất lượng và tính tin cậy của ứng dụng của mình. Việc áp dụng các thực tiễn kiểm thử tốt không chỉ giúp bạn phát hiện và sửa chữa các lỗi sớm hơn mà còn giúp bạn xây dựng các ứng dụng React và Redux chất lượng cao.

Hãy thường xuyên kiểm thử các ứng dụng của bạn và tận dụng tối đa sức mạnh của Redux Testing Library để đạt được mục tiêu này!

#redux-testing-library #kiểm-thử-tích-hợp #redux #react

Các bạn có thể tham khảo thêm nguồn khác:

React Redux | Testing Library

React Redux. Moved to Writing Tests | Redux. Edit this page. Last updated on Nov 4, 2020 by Matan Borenkraout. Previous. React Intl.>

Redux - A predictable state container for JavaScript apps. | Redux

Redux helps you write applications that behave consistently, run in different environments (client, server, and native), and are easy to test. Centralized Centralizing your application's state and log>

Writing Tests | Redux

React Testing Library is a simple and complete React DOM testing utility that encourages good testing practices. It uses ReactDOM's render function and act from react-dom/tests-utils. (The Testing Lib>

Using Redux? React Testing Library Doesn't Care!

Aug 28, 2021Our Redux App Under Test In Within Reach: Testing Lists with React Testing Library, we tested a simple component that manages a list of characters from The Office. We're going to use this>

10 Testing Redux Best Practices - CLIMB

Dec 17, 2022Redux is a popular state management library for JavaScript applications, and it's important to test your Redux code to make sure it's working correctly. In this article, we'll discuss 10 b>

Getting Started with Redux and Testing Library - Medium

Aug 13, 2021Redux React Testing Library React Programming Java Script More from JavaScript in Plain English Follow New JavaScript and Web Development content every day. Follow to join 2.5M+ monthly re>

Test React Component using Redux and react-testing-library

redux react-redux react-testing-library Share Improve this question Follow asked Jan 21, 2019 at 4:28 Charklewis 3,703 4 27 61 It doesn't look like you're passing in or defining an initialState? - dan>

Testing Redux with Jest - DEV Community ????‍????????‍????

Redux is a state management library that helps to make state management predictable and testable. Action creators and reducers in particular are testable. Redux-Saga is a middleware that promises to m>

Best Practices for Testing a React/Redux Toolkit App - XTIVIA

The React Testing Library encourages best practices by helping test React components in a user-centric way. With React Testing Library, you can mock-render React components, fire events on them, and t>

Testing Redux Connected React Components Using Jest - Rusith's blog

As we are going to test the component, First thing we have to do is to isolate it. A Redux based component can communicate in two ways. It can dispatch actions and it can take store updates as props.>

Redux - Testing - tutorialspoint.com

Testing Redux code is easy as we mostly write functions, and most of them are pure. So we can test it without even mocking them. Here, we are using JEST as a testing engine. It works in the node envir>

How to test Redux-connected React components | Felix Gerschau

Aug 29, 2021In this tutorial, we'll use the following tools for testing. Jest. Testing library. Both of these libraries are included in Create-React-App (CRA). If you don't use CRA, you can install th>

Testing Redux-connected components with React Testing Library

Nov 7, 2021Redux-connected components testing Testing Redux-connected components with React Testing Library Angelos Chalaris · React, Testing · Nov 7, 2021 Testing Redux-connected components with Reac>

React Unit Test Handbook + Redux Testing Toolkit

Nov 9, 2022Under the hood, you now have an application that uses the React Testing library combined with Jest (a testing framework). Together, they have pretty much everything that you will need for t>

mocking redux with react-testing-library | /*code-comments*/

May 28, 2021mocking redux with react-testing-library 2021-05-28 | ~ 3 min read | 549 words In a previous post about abstracting utilities in Jest, I demonstrated how to create a wrapper for the render>

Testing a Redux Hooked App. How to write integration tests using… | by ...

An integration test with React Testing Library. We first render our App component. Then toggle the Veg Only checkbox and at last check that the right food items are shown in the menu. By reading the a>

GitHub - jabro86/redux-testing-library: Testing utilities for react and ...

redux-testing-library. Simple and maintainable tests for your react/redux application inspired by react-testing-library. Features. simple data-driven integration tests; dispatch actions, wait for stor>

Testing | Redux-Saga - js

redux-saga-testing library provides a method sagaHelper that takes your generator and returns a value that works a lot like Jest's it () function, but also advances the generator being tested. The res>

React: Mocking with MSW, React Testing Library, and Jest with Redux ...

Testing user behavior with character mocks First, we will need to create a __tests__directory within the src/features/characterdirectory. Our tests should be as close as possible to the file we...>

React Testing Library | Testing Library

Aug 9, 2022React Testing Library builds on top of DOM Testing Library by adding APIs for working with React components. Projects created with Create React App have out of the box support for React Tes>

Testing APIs with React and Redux. Part one - testing in a React app ...

The first method is to use a JavaScript test runner (such as Mocha) and combine this with an assertion library (e.g. Chai or Expect). This can then be combined with a utility to assert the rendered ou>

Testing Redux Connected React Components with React Testing Library ...

Your test of these components gets a lot more complicated, but as I'll show you, we've got this. [1:28] At the top of your file, go ahead and import Provider from "react-redux". Import store from "../>

Evaluating Redux Saga Test Libraries - Scott Logic

Testing without any helper library involves manually stepping through the saga function and asserting effects as needed. It is most useful for testing the exact order of effects that are yielded. Redu>

Redux Form and Typescript testing with React Testing Library

Feb 23, 2022Unit tests for Redux Form usually consist of testing the correct rendering of the form and the correct interaction with the form. Tests for rendering include rendering without initial valu>

React Native Testing Library with Redux | blog {callstack}

Testability of Redux reducers is well known, because of their pure functional nature, however proper testing of middleware like Saga or Thunk is somewhat more complex. Additionally testing all of thes>

@testing-library/react - npm

Simple and complete React DOM testing utilities that encourage good testing practices.. Latest version: 13.4.0, last published: 4 months ago. Start using @testing-library/react in your project by runn>

React-Redux testing: mocking useSelector and useDispatch

Tom Szpytman. 22 Followers. Full-stack + Product. Available for hire either as an independent contractor, or as part of a voliyo.dev team. Inquiries: mail [at] voliyo.dev. Follow.>

Testing React / Redux Apps with Jest & Enzyme - DigitalOcean

The series. Part 1: Installation & Setup. Part 2: Testing React Components. Part 3: Testing Redux Actions (this post) Part 4: Testing Redux Reducers. We'll now be moving into testing on the Redux side>

Testing Redux with Jest - Coding Ninjas CodeStudio

May 12, 2022Testing asynchronous actions are tricky, which is why middleware like redux-saga and redux-thunk is very handy, especially when it comes to testability. In Redux, Middleware functions wrap>


Tags:
SHARED HOSTING
70% OFF
$2.99/mo $0.90/mo
SHOP NOW
RESELLER HOSTING
25% OFF
$12.99/mo $9.74/mo
SHOP NOW