Test with Storybook

TheDevStory
3 min readAug 2, 2022

Set Test component

First of all, we need to set test.tsx component that we want to apply to our component.

import Button from "./Button";
import { render, screen } from "@testing-library/react";
test("renders learn react link", () => {
render(<Button />);
expect(screen.getByRole("button")).toHaveTextContent(/Hello /i);
});

So this is a normal test libray setting in React. But we want to use this with our Storybook setting. Its easy to apply first we can just add our Storybook component in test component.

import { RedButton } from "./Button.stories";
import { render, screen } from "@testing-library/react";
test("renders learn react link", () => {render(<RedButton {...RedButton.args} />);
expect(screen.getByRole("button")).toHaveTextContent(/Red/i);
});

After we made this, we can check test library.

Test Command

Test command is also easy. Only thing you need to do is just type this.

yarn test

But, for better Test experience we need to add some lines in package.json.

"jest": {
"collectCoverageFrom": [
"<rootDir>/src/components/**/*.{ts,tsx}",
"!**/node_modules/**",
"!**/*.stories.{ts,tsx}"
]
},

Just add upper code inside in your package.json. All this code mean that ㅜot testing unnecessary elements like node modules, and stories.

And also i want to add some new script

"test:coverage": "react-scripts test --watchAll=false --coverage",

and after this you can run yarn test:coverage . Then we can see like this.

But you can see that our test element is not fill 100%.

So let’s fix that.

Make test 100%

First we need to check index.html that in Coverage folder. I will express the position in a tree structure.

react App
|_ coverage
|_ Icov-report
|_ index.html

in there you can see what we miss.

we can easily find that we miss sm and lg type button. So let’s add that in our Button.test.tsx.

test("should render SmButton", () => {
render(<SmButton {...SmButton.args} />);
expect(screen.getByRole("button")).toHaveTextContent(/Small Button/i);
});
test("should render LgButton", () => {
render(<LgButton {...LgButton.args} />);
expect(screen.getByRole("button")).toHaveTextContent(/Large Button/i);
});

If we test after this we can find that we pass all test element.

How to test custom styled component

If you want to test specific style customized then you can add other test option like below.

test("should render RedButton", () => {
render(<RedButton {...RedButton.args} />);
expect(screen.getByRole("button")).toHaveTextContent(/Red/i);
expect(screen.getByRole("button")).toHaveStyle("backgroundColor: red");
});

with expectmethod inside of test you can define what we want to test in the component.

--

--

TheDevStory

A web developer crafting online experiences. Also football(soccer) coach and Spanish Learner.