DEV Community 👩‍💻👨‍💻

Junichi Takahashi
Junichi Takahashi

Posted on

How to set up Next.js + Storybook + jest

Storybook is a testing tool.
This article describes how to set up Next.js + Storybook + jest.

Next.js + Storybook

How to set up Next.js + Storybook
https://dev.to/jtakahashi64/how-to-set-up-storybook-with-nextjs-4a3a

Install

npm i --save-dev ts-node
npm i --save-dev jest
npm i --save-dev jest-environment-jsdom
npm i --save-dev ts-jest
npm i --save-dev @storybook/testing-react
npm i --save-dev @testing-library/jest-dom
npm i --save-dev @testing-library/react
Enter fullscreen mode Exit fullscreen mode

Settings

# package.json

{
  "scripts": {
    "test": "jest"
  }
}
Enter fullscreen mode Exit fullscreen mode
// jest.config.ts

export default {
  preset: "ts-jest",
  testEnvironment: "jsdom",
  globals: {
    "ts-jest": {
      tsconfig: "./tsconfig.jest.json",
    },
  },
    moduleNameMapper: {
    "@/(.*)": "<rootDir>/src/$1",
  },
};
Enter fullscreen mode Exit fullscreen mode
# tsconfig.jest.json

{
  "extends": "./tsconfig",
  "compilerOptions": {
    "jsx": "react-jsx"
  }
}
Enter fullscreen mode Exit fullscreen mode

Write

// src/components/example.test.tsx

import { composeStories } from "@storybook/testing-react";
import { render } from "@testing-library/react";
import "@testing-library/jest-dom";

import * as stories from "@/components/example.stories";

describe("components/Example", () => {
  const { Default } = composeStories(stories);

  test("Show text", () => {
    const { getByTestId } = render(<Default text="This is a test text." />);
    const text = getByTestId("text");
    expect(text).toHaveTextContent("This is a test text.");
  });
});
Enter fullscreen mode Exit fullscreen mode

Run

npm run test
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.