This is the first day of my participation in the Gwen Challenge in November. Check out the details: the last Gwen Challenge in 2021

preface

Testing code can be a confusing practice for many developers. This is understandable, since writing tests requires more effort, more time, and the ability to anticipate possible use cases. Startups and developers working on smaller projects often tend to ignore testing altogether due to a lack of resources and manpower.

However, I think components should be tested for two reasons:

  1. It gives you more confidence in your code.
  2. Testing can improve your productivity.

In this article, I walk you through everything you need to write tests for the React component. We’ll also cover some best practices and techniques. Let’s get started!

Introduction to Jest unit testing

Common selector

GetByRole: Queries based on the role attribute specified on the element

GetByText: Queries based on text child nodes of the element

GetByTestId: querying the information based on the user-defined attribute data on the element

The timer

Jest. UseFakeTimers: Applies for the use of timers from jEST

Jest. RunAllTimers: Executes the timer

Jest. UseRealTimers: Destroys the timer

hooks

RenderHook: For rendering, it has two arguments: callback for hooks and config for configuring initialization values

Act: The user performs a hook to update a state

Unit testing

The target of a unit test can be a function, a class, or a module. Unit tests should be isolated and independent. For a given input, the unit test checks the result. By catching problems early and preventing bugs from returning, it helps us ensure that all parts of the code work as expected.

Integration testing

Even if all the unit tests passed, our application could still crash. Integration testing is the process of testing across modular units/modules and is a good way to ensure that our code works as a whole.

End-to-end Testing (E2E)

Unlike other types of tests, E2E tests are always run in a browser (or browser-like) environment. It could be an actual browser that you can open and run tests in; It could also be a Headless browser environment, which is a browser with no user interface. E2E testing focuses on simulating real users in the application we are running (for example, simulating behaviors like scrolling, clicking, and typing) and checking that our application is performing well from the perspective of real users.

The next chapter will enter the code level, interested partners can wait for the next update (ongoing update)