Welcome to our comprehensive guide on using the Testing Library with Vite! This tutorial is designed for both beginners and intermediates, with a focus on practical, real-world examples. Let's dive in! šÆ
Testing Library is a suite of simple and consistent testing utilities that encourage good testing practices. It's designed to help you write tests that are easy to understand, fast, and reliable. š
Combining Vite and Testing Library offers numerous benefits:
Before we start, make sure you have:
npm install -g viteLet's create a new Vite project:
vite create vite-testing-library
cd vite-testing-libraryWe'll use @testing-library/react for React components testing:
npm install --save-dev @testing-library/react @testing-library/jest-domNow, let's create a simple React component and write a test for it:
src folder, create a new file App.js:// src/App.js
import React from 'react';
function App() {
return (
<div>
<h1>Hello, World!</h1>
</div>
);
}
export default App;__tests__ in the src folder:mkdir src/__tests____tests__ folder, create a new file App.test.js:// src/__tests__/App.test.js
import React from 'react';
import { render } from '@testing-library/react';
import App from './App';
test('renders App correctly', () => {
const { getByText } = render(<App />);
const linkElement = getByText(/hello, world!/i);
expect(linkElement).toBeInTheDocument();
});Vite provides a test command for running tests. In the project root, run:
npm run testYou should see your test passing! š
Use the screen function to test the rendered output:
// src/__tests__/App.test.js
import { screen } from '@testing-library/react';
// ...
test('renders App correctly', () => {
render(<App />);
const heading = screen.getByText(/hello, world!/i);
expect(heading).toBeInTheDocument();
});What is the main benefit of using Testing Library with Vite?
That's it for now! In the next lesson, we'll dive deeper into Testing Library and explore more advanced testing techniques. Stay tuned! š
š Note: Don't forget to check out CodeYourCraft's Vite documentation for more resources on Vite!
Types:
React.FC: Functional React Componentrender: Renders a React component and returns utility functionsgetByText: Gets the first element with the given text contentscreen: Renders a React component and returns utility functions to query elements in the documenttoBeInTheDocument: Asserts that the element is present in the document treeexpect: Assertion function from Jest