React: Tests with Bun:test

Carlos Costa

Bun is a fast all-in-one JavaScript runtime that we can use to run our React app. This note is to demostrate how to set up Bun with Next.js to test our React components.

First of all, let’s create our project:

npx create-next-app@latest np --ts --src-dir --app --import-alias --empty --use-bun --tailwind

Now, let’s clear the home page.

//src/app/page.tsx
export default function Home() {
  return (
    <main className="min-h-screen flex justify-center items-center">
      <h1> Hello world! </h1>
    </main>
  );
}

So, let’s React Testing Library and Happy Dom.

bun install @happy-dom/global-registrator @testing-library/react -d

We will need two files in root directory: bunfig.toml and happydom.ts.

bunfig.toml

[test]
preload = "./happydom.ts"

happydom.ts

import { GlobalRegistrator } from "@happy-dom/global-registrator";
GlobalRegistrator.register();

Now, let’s create our __tests__ directory and create a file home.test.tsx.

import { expect, test, describe } from 'bun:test'
import { render, screen } from '@testing-library/react'
import Home from '../src/app/page'

describe('Home', () => {
  test('renders', () => {
    render(<Home />)

    expect(screen.getByText('Hello world!')).toBeTruthy()
  })
})

Finally, let’s run our tests: bun test.

 bun test
bun test v1.1.21 (70ca2b76)

__tests__\home.test.tsx:
 Home > renders [16.00ms]

 1 pass
 0 fail
 1 expect() calls
Ran 1 tests across 1 files. [397.00ms]