I'm Samuel FajreldinesI am a specialist in the entire JavaScript and TypeScript ecosystem (including Node.js, React, Angular and Vue.js) I am expert in AI and in creating AI integrated solutions I am expert in DevOps and Serverless Architecture (AWS, Google Cloud and Azure) I am expert in PHP and its frameworks (such as Codeigniter and Laravel). |
Samuel FajreldinesI am a specialist in the entire JavaScript and TypeScript ecosystem. I am expert in AI and in creating AI integrated solutions. I am expert in DevOps and Serverless Architecture I am expert in PHP and its frameworks.
|
In today's fast-paced development environment, testing has become an indispensable part of the software development lifecycle. For React applications, Jest is one of the most popular testing frameworks due to its simplicity and powerful features. In this guide, we'll explore what Jest is, why it's essential for React development, and provide a comprehensive tutorial on how to create and run tests in your React projects.
Jest is an open-source testing framework developed by Facebook, designed specifically for JavaScript applications. It provides an easy way to write tests with an intuitive and familiar syntax, making it an excellent choice for both beginners and experienced developers.
When developing React applications, ensuring that components work as expected is crucial. Jest provides tools specifically designed to test React components effectively:
Let's walk through setting up Jest in a React project.
First, create a new React application using Create React App:
npx create-react-app my-app
cd my-app
Create React App comes with Jest pre-configured, so you can start writing tests immediately.
If you have an existing React project without Jest, you can install it using:
npm install --save-dev jest babel-jest @babel/preset-env @babel/preset-react react-test-renderer
Then, add the following to your package.json
to configure Jest:
"scripts": {
"test": "jest"
},
"jest": {
"setupFilesAfterEnv": ["<rootDir>/src/setupTests.js"]
}
Let's create a simple component and write a test for it.
Create a new file src/components/Greeting.js
:
import React from 'react';
function Greeting({ name }) {
return <h1>Hello, {name}!</h1>;
}
export default Greeting;
Create a test file src/components/Greeting.test.js
:
import React from 'react';
import { render, screen } from '@testing-library/react';
import Greeting from './Greeting';
test('renders greeting message', () => {
render(<Greeting name="World" />);
const greetingElement = screen.getByText(/Hello, World!/i);
expect(greetingElement).toBeInTheDocument();
});
Run the test using:
npm test
Jest will find the test files and execute them, reporting the results in your terminal.
Let's break down the test we wrote:
Testing how users interact with your components is essential.
Suppose we have a button that increments a counter:
// Counter.js
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}
export default Counter;
// Counter.test.js
import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import Counter from './Counter';
test('increments count on button click', () => {
render(<Counter />);
const buttonElement = screen.getByText(/Click me/i);
fireEvent.click(buttonElement);
expect(screen.getByText(/You clicked 1 times/i)).toBeInTheDocument();
});
Snapshot testing is a way to test the UI of your components.
// Greeting.test.js
import React from 'react';
import renderer from 'react-test-renderer';
import Greeting from './Greeting';
test('Greeting component matches snapshot', () => {
const tree = renderer.create(<Greeting name="World" />).toJSON();
expect(tree).toMatchSnapshot();
});
When you run the test for the first time, Jest will create a snapshot file. Subsequent runs will compare the rendered output to this snapshot.
Jest allows you to mock functions or modules to control their behavior during tests.
Suppose your component uses an API module:
// api.js
export const fetchData = () => {
// fetch data from an API
};
You can mock this module in your tests:
jest.mock('./api', () => ({
fetchData: jest.fn(() => Promise.resolve({ data: 'mock data' })),
}));
// DataComponent.test.js
import React from 'react';
import { render, screen, waitFor } from '@testing-library/react';
import DataComponent from './DataComponent';
import { fetchData } from './api';
test('displays fetched data', async () => {
fetchData.mockResolvedValueOnce({ data: 'mock data' });
render(<DataComponent />);
await waitFor(() => expect(screen.getByText(/mock data/i)).toBeInTheDocument());
});
Jest can generate code coverage reports to help you understand how much of your code is tested.
Run Jest with the --coverage
flag:
npm test -- --coverage
Review the generated reports to identify untested parts of your application.
Integrate Jest tests into your CI pipeline to ensure code quality in every build.
Create a .github/workflows/main.yml
file:
name: Node.js CI
on:
push:
branches: [ main ]
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [14.x, 16.x]
steps:
- uses: actions/checkout@v2
- name: Use Node.js $
uses: actions/setup-node@v2
with:
node-version: $
- run: npm install
- run: npm test -- --coverage
- uses: actions/upload-artifact@v2
with:
name: coverage-report
path: coverage/
Testing is a critical part of developing robust React applications, and Jest provides a powerful yet simple framework to achieve this. By following this guide, you should now have a solid understanding of how to set up Jest, write various types of tests, and integrate testing into your development workflow.
By mastering Jest, you'll ensure that your React applications are reliable, maintainable, and bug-free, making you a more effective developer.
About Me
Since I was a child, I've always wanted to be an inventor. As I grew up, I specialized in information systems, an area which I fell in love with and live around it. I am a full-stack developer and work a lot with devops, i.e., I'm a kind of "jack-of-all-trades" in IT. Wherever there is something cool or new, you'll find me exploring and learning... I am passionate about life, family, and sports. I believe that true happiness can only be achieved by balancing these pillars. I am always looking for new challenges and learning opportunities, and would love to connect with other technology professionals to explore possibilities for collaboration. If you are looking for a dedicated and committed full-stack developer with a passion for excellence, please feel free to contact me. It would be a pleasure to talk with you! |
SecurityScoreCard
Nov. 2023 - Present
New York, United States
Senior Software Engineer
I joined SecurityScorecard, a leading organization with over 400 employees, as a Senior Full Stack Software Engineer. My role spans across developing new systems, maintaining and refactoring legacy solutions, and ensuring they meet the company's high standards of performance, scalability, and reliability.
I work across the entire stack, contributing to both frontend and backend development while also collaborating directly on infrastructure-related tasks, leveraging cloud computing technologies to optimize and scale our systems. This broad scope of responsibilities allows me to ensure seamless integration between user-facing applications and underlying systems architecture.
Additionally, I collaborate closely with diverse teams across the organization, aligning technical implementation with strategic business objectives. Through my work, I aim to deliver innovative and robust solutions that enhance SecurityScorecard's offerings and support its mission to provide world-class cybersecurity insights.
Technologies Used:
Node.js Terraform React Typescript AWS Playwright and Cypress