Skip to main content

Writing tests

Testing 101

We strongly recommend reading through the RTL and Jest docs to gain an understanding of their APIs

Naming

All test files should be named: <component>.test.js this way Jest can automatically pick this file as a test without specifying in a config.

Location

Test location differs per repository, please consult the repo's README.md for more details.


The basics

A quick example to show and give an understanding of how jest and rtl render tests, given:

component.js
import Button from "./button";

const Component = () => (
<div className={"class-1"}>
Im a component
<Button label={"labeled"}>Click me!</Button>
</div>
)

component.test.js
import React from "react";
import {render, screen} from "test-utils";
import userEvent from "@testing-library/user-event";
import "@testing-library/jest-dom";

import Component from './component'

describe("Component", () => {
test("should render button", () => {
render(<Component/>);
expect(screen.getByRole("button")).toHaveTextContent("Click me!");
})
})

Since jest uses the js-dom to render components we have to work directly with the dom, we cannot tap into the react components or props.

The expected output from render(<Component/>) would be:

render(<Component/>)
<div class="class-1">
Im a component
<button aria-label="labeled">
Click me!
</button>
</div>

As you can see, this is the rendered HTML to a browser dom. Therefore when we expect we work with what is given above.