Chuck's Academy

Testing JavaScript and DOM with DOM Testing Library

Writing Your First Unit Tests with Testing Library

In this chapter, we will focus on writing our first unit tests using DOM Testing Library. Unit tests allow you to verify small parts of your code in isolation, ensuring each component works as expected.

Creating a Simple Component

To start, let's create a basic component in HTML and JavaScript:

File index.html:

html

File index.js:

javascript

Writing a Unit Test

Let's write a unit test to verify that the button is rendered correctly in the DOM.

File button.test.js:

javascript

Understanding the Test

  1. Initial Setup:

    • beforeEach: Runs before each test, creating a div container and appending it to the body.
    • afterEach: Cleans up the DOM by removing the container after each test.
  2. Writing the Test:

    • We call the renderButton function passing the container.
    • We use the getByText function from DOM Testing Library to find the button by its text.
    • We use Jest's expect to verify that the button is in the DOM.

[Placeholder for an explanatory image: A simple diagram showing the test flow from creating the container, rendering the button, to verifying]

Additional Tests

Let's look at other unit tests that can be applied to the same component.

Verify the Existence of an Attribute

We will verify that the button has the id attribute set correctly.

javascript

Verify Click Behavior

Suppose we want to add a click behavior to our button.

Modified file index.js:

javascript

Add test in button.test.js:

javascript

Conclusion

In this chapter, we learned how to write our first unit tests using DOM Testing Library. We saw how to verify the presence of elements in the DOM and how to simulate events to validate component behavior.

These initial unit tests lay the groundwork for more advanced tests that we will explore in upcoming chapters, where we will look at how to test more complex components and their interactions.


Ask me anything