Testing
Testing react applications in VS Code

5 min read
#TestingTable Of Content
- React Testing in VS Code: A Comprehensive Guide
- Creating the CRUD Application
- Tech Stack
- Features
- Setting Up the Project
- Implementing CRUD Features
- Create
- Read
- Update & Delete
- Testing the Application
- Unit Testing with Jest & React Testing Library
- End-to-End UI Testing with Playwright
- End-to-End Testing with Keploy
- API Testing with Keploy
- Automated Testing in VS Code with Keploy AI Extension
- Why Use Keploy AI Extension?
- Installing Keploy AI Extension in VS Code
- Using Keploy AI for API Testing
- Benefits of Keploy AI Extension in VS Code
- Debugging and Optimization in VS Code
- Using VS Code Debugger
- Performance Optimization
- Linting and Code Formatting
- Deploying the Application
- Deploying to Vercel
- Setting Up CI/CD with GitHub Actions
- Conclusion
- FAQs
React Testing in VS Code: A Comprehensive Guide
Creating the CRUD Application
Tech Stack
- React for building UI components.
- TailwindCSS (optional) for styling.
- JSON Server for a mock API.
Features
- Create: Add a new item.
- Read: Display a list of items.
- Update: Edit an existing item.
- Delete: Remove an item.
Setting Up the Project
- Initialize a React project:
npx create-react-app react-testing-demo --template cra-template-pwa cd react-testing-demo
- Install dependencies:
npm install tailwindcss json-server axios react-query
- Configure TailwindCSS (if using):
npx tailwindcss init
- Set up
json-server
indb.json
:{ "items": [ { "id": 1, "name": "Item 1" }, { "id": 2, "name": "Item 2" } ] }
- Run the mock API:
npx json-server --watch db.json --port 3001
Implementing CRUD Features
Create
import { useState } from 'react';
import axios from 'axios';
const AddItem = ({ onAdd }) => {
const [name, setName] = useState('');
const addItem = async () => {
const res = await axios.post('http://localhost:3001/items', { name });
onAdd(res.data);
};
return (
<div>
<input value={name} onChange={(e) => setName(e.target.value)} />
<button onClick={addItem}>Add Item</button>
</div>
);
};
export default AddItem;
Read
import { useEffect, useState } from 'react';
import axios from 'axios';
const ItemList = () => {
const [items, setItems] = useState([]);
useEffect(() => {
axios.get('http://localhost:3001/items').then((res) => setItems(res.data));
}, []);
return (
<ul>
{items.map((item) => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
};
export default ItemList;
Update & Delete
Implement EditItem
and DeleteItem
components similarly.
Testing the Application
Unit Testing with Jest & React Testing Library
- Install testing libraries:
npm install --save-dev @testing-library/react jest
- Write a test for
AddItem.js
:import { render, fireEvent } from '@testing-library/react'; import AddItem from './AddItem'; test('adds a new item', () => { const mockOnAdd = jest.fn(); const { getByText, getByRole } = render(<AddItem onAdd={mockOnAdd} />); fireEvent.change(getByRole('textbox'), { target: { value: 'New Item' } }); fireEvent.click(getByText('Add Item')); expect(mockOnAdd).toHaveBeenCalled(); });
End-to-End UI Testing with Playwright
- Install Playwright:
npm install --save-dev @playwright/test
- Write a Playwright test:
import { test, expect } from '@playwright/test'; test('add an item', async ({ page }) => { await page.goto('http://localhost:3000'); await page.fill('input', 'New Item'); await page.click('text=Add Item'); expect(await page.textContent('ul')).toContain('New Item'); });
End-to-End Testing with Keploy
- Install Keploy:
curl -sSfL https://get.keploy.io | sh
- Start Keploy in test mode:
keploy test -c "npm start"
- Generate test cases by running API requests via Postman or UI.
- Run Keploy tests to validate API responses:
keploy replay
API Testing with Keploy
- Install Keploy:
npm install --save-dev keploy
- Record API calls:
keploy record --app http://localhost:3001
- Replay recorded requests for testing:
keploy replay
Automated Testing in VS Code with Keploy AI Extension
Keploy AI provides an automated API testing solution directly integrated into VS Code, enabling a one-click approach to recording and replaying API interactions.
Why Use Keploy AI Extension?
- Single-Click Automation: Run complete API tests without manual scripting.
- Faster Testing Cycles: Eliminates the need for writing complex API mocks.
- Seamless Integration: Works directly within VS Code.
- Intelligent Test Case Generation: Automatically records API calls as test cases.
Installing Keploy AI Extension in VS Code
- Open VS Code and navigate to the Extensions Marketplace.
- Search for Keploy AI and click Install.
- Open the Command Palette (
Ctrl+Shift+P
) and typeKeploy: Start Recording
.
Using Keploy AI for API Testing
- Start Recording API Calls:
- Run your React application and backend server.
- Click on Keploy: Start Recording in the VS Code extension panel.
- Perform API requests via your frontend application.
- Generate Test Cases Automatically:
- Keploy will capture all API requests and responses.
- The extension will generate JSON test cases.
- Replay Tests with One Click:
- Click Keploy: Run Tests to replay API calls.
- Ensure that API responses remain consistent.
Benefits of Keploy AI Extension in VS Code
- Speeds up testing by automating API validation.
- Reduces human errors by generating test cases dynamically.
- Enhances debugging with real-time request tracking.
- Simplifies API mocking by eliminating manual mocks.
Debugging and Optimization in VS Code
Using VS Code Debugger
- Open VS Code, go to
Run and Debug
. - Add a breakpoint in
AddItem.js
. - Click
Start Debugging
to inspect the code.
Performance Optimization
- Use React.memo for component optimization.
- Use lazy loading with
React.lazy()
. - Optimize API calls with React Query.
Linting and Code Formatting
- Install ESLint and Prettier:
npm install --save-dev eslint prettier eslint-plugin-react-hooks
- Configure
.eslintrc.json
:{ "extends": ["react-app", "plugin:react-hooks/recommended"] }
Deploying the Application
Deploying to Vercel
- Install Vercel CLI:
npm install -g vercel
- Deploy:
vercel
Setting Up CI/CD with GitHub Actions
Create .github/workflows/test.yml
:
name: CI/CD
on: push
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Install dependencies
run: npm install
- name: Run tests
run: npm test
Conclusion
- Testing improves application reliability and maintainability.
- Use Jest for unit tests, Playwright for UI tests, and Keploy for API tests.
- Debugging in VS Code streamlines development.
- Deploying with Vercel and GitHub Actions ensures a smooth workflow.
FAQs
- Why use Jest and React Testing Library?
- They provide easy-to-use tools for testing React components.
- What is Playwright used for?
- It automates UI testing and simulates user interactions.
- Why test APIs with Keploy?
- It helps in recording, replaying, and validating API calls.
- How to optimize React performance?
- Use memoization, lazy loading, and React Query.
- How to debug in VS Code?
- Use breakpoints and the built-in debugger for efficient debugging.