Unit test is for:

  1. Test Drive Development. It might take some extra time in the early stage of development, but it will eventually save more time by preventing bugs from edge cases
  2. Ensures Component and Function Reliability
  3. Speeds Up Debugging and Development
  4. Supports Continuous Integration & Deployment (CI/CD)
  5. Enhances Code Maintainability
  6. Improves Developer Confidence

1. Initiate a Next.js Project and install Jest

Following this tutorial:

Testing: Jest

You need to install these packages to make Jest work for a Typescript project:

npm install -D jest jest-environment-jsdom @testing-library/react @testing-library/dom @testing-library/jest-dom ts-node

2. First test

It is suggested to write a must-success-test to make sure that Jest is installed and run properly.

I suggest put all test files under __test__ folder in the root directory. In a structure like the image to the right.

create a basic.test.tsx file that run a very basic test that not involving any code of the project.

import '@testing-library/jest-dom';
import { render, screen } from '@testing-library/react';
import Page from '../src/app/test/page';

describe('Jest', () => {
  it('can run the simplest test', () => {
    render(<Page />);
    const heading = screen.getByRole('heading', { level: 1 });
    expect(heading).toBeInTheDocument();
  });
});

Notice that the <Page /> component is not the a real testing component, it should be simple like this:


```tsx
export default function Page() {
  return (
    <div>
      <h1>Test Page</h1>
    </div>
  );
}

Screenshot 2025-03-14 at 14.53.16.png

3. Unit tests for general functions

Let use a function for example.

I am going to write a segmentHeight function that take three parameters: contentHeight, currentPageLeftHeight, fullPageHeight. The function should return an array of number that represents how many page needed and how many height it is going to be used by content (contentHeight).

For example, segementHeight(500, 300, 800) should return [300, 200] .

Then I will have my first test:

import { segmentHeight } from '@/utils/utils';

describe('segmentHeight', () => {
  const fullPageHeight = 800;
  it('should return the correct heights for a single page', () => {
    const cardRecordedHeight = 500;
    const leftHeight = 300;

    const result = segmentHeight(
      cardRecordedHeight,
      leftHeight,
      fullPageHeight
    );

    expect(result).toEqual([300, 200]);
  });
})