JEST is a testing library inspired by the way unit tests are written in JavaScript. Its designed for ease of use, but can also be used to integrate synchronous and asynchronous non-trivial code as test data.
npx create-react-app react-jest-tutorial
npm install --save-dev @testing-library/react
Import the folder into Visual Studio Code.
Now open Explorer in VS code and you can see App.test.js file is created.
function App() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer">
Learn React
</a>
</header>
</div>
);
}
test('renders learn react link', () => {
render(<App />);
const linkElement = screen.getByText(/learn react/i);
expect(linkElement).toBeInTheDocument();
});
// or
test('renders learn react link', () => {
render(<App />);
expect(screen.getByText(/learn react/i)).toBeInTheDocument();
});
npm test
Above you can see 1 Passed test. This test is checking whether Learn React text available in App.js file for not.
Lets rename text in the file to Learn Java and test the result.
function App() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer">
Learn Java
</a>
</header>
</div>
);
}
npm test
This time test is searching for Learn React text and that text is not found so it got failed.