When you're done creating a React element in your project, you may wonder how you would test it. There are various methods for testing a React component. Here, we will talk about the most basic test you could do called smoke test. We will use Jest for this purpose.
If you used create-react-app
for creating your project, then you don't need to install anything. If, however, you didn't use create-react-app
, just simply install Jest to your project like this:
$ npm install --save-dev jest
and add the following lines to your package.json
:
{
"scripts": {
"test": "jest"
}
}
Smoke Test
Smoke test is used to verify whether a component renders without throwing errors. Let's say that you have a card component that contains a button and a text. Let's call this component MyCard
. Here's the code inside:
// MyCard.js
import React from "react";
const MyCard = () => {
const [counter, setCounter] = React.useState(0);
const handleClick = () => {
setCounter(counter++);
}
return (
<div>
<p>Counter: {counter}</p>
<button onClick={handleClick}>Increment</button>
</div>
);
}
export default MyCard;
To smoke test MyCard
component, do the following steps:
- Create a new file called
MyCard.test.js
in the same folder asMyCard.js
. - Write the following code inside
MyCard.test.js
:
import React from "react"; import ReactDOM from "react-dom"; import MyCard from "./MyCard"; it("renders without crashing", () => { const div = document.createElement("div"); ReactDOM.render(<MyCard />, div); });
- Open a terminal in the project's root folder and run the following command:
$ npm test
Each time you edit your files, the tests will be redone automatically.
To run the test with coverage, use this command instead: (Note that this will be slower than without using coverage)
$ npm test -- --coverage
That's it! Next week we will talk about more sophisticated React component's testing methods!