{"id":1158,"date":"2023-12-29T02:16:08","date_gmt":"2023-12-29T02:16:08","guid":{"rendered":"https:\/\/bluesockets.com\/?p=1158"},"modified":"2024-02-05T02:01:54","modified_gmt":"2024-02-05T02:01:54","slug":"react-js-unit-testing-vitest-husky-lint-staged-eslint-prettier","status":"publish","type":"post","link":"https:\/\/bluesockets.com\/react\/react-js-unit-testing-vitest-husky-lint-staged-eslint-prettier\/","title":{"rendered":"React.js Vite Unit Testing (Vitest, Husky, lint-staged, ESLint, Prettier)"},"content":{"rendered":"\n
Creating a React application with Vite<\/a> has now become the preferred way rather than using create-react-app<\/a>. Vite provides a much faster and simpler development environment, however unlike create-react-app, it does not come with the packages needed for unit testing React applications out of the box.<\/p>\n\n\n\n In this article, we will explore how to set up unit testing for a production-ready React + Typescript Vite application. We’ll set up testing with the lightweight and fast Vitest<\/a> testing framework and the React Testing Library<\/a>. We’ll also configure linting and formatting with ESLint and Prettier to catch issues early. And we’ll use Husky and lint-staged to automatically run tests and linting on git commits before code is pushed. By the end, you’ll have a solid testing setup that catches bugs, prevents regressions, and helps enforce code quality standards while developing and merging code changes.<\/p>\n\n\n Vitest vs Jest<\/p> Jest is a widely used testing framework for JavaScript. It offers features like built-in support for mocking and snapshot testing making it a comprehensive choice for JavaScript testing. On the other hand, Vitest is a JavaScript unit testing framework designed to complement Vite. Vitest focuses on speed and simplicity, with tests running significantly faster than Jest in some cases. It also offers compatibility with most of the Jest API, making it a viable alternative to Jest. <\/p>\n\n\n\n For small to medium sized projects, Vitest’s simplicity often makes it preferable to Jest which can be overkill. But for larger codebases with more complex test needs, features like snapshot testing or Jest’s rich ecosystem may make it a better choice.<\/p>\n\n<\/div><\/div>\n\n Why use Typescript?<\/p> TypeScript offers several advantages over JavaScript, primarily due to its strong typing system. By providing static typing, TypeScript allows developers to catch errors during development rather than at runtime, enhancing code quality and reducing bugs. Learn more<\/a>.<\/p>\n\n<\/div><\/div>\n<\/div>\n\n Assuming you already have your React Vite project setup<\/a> ( The first step is to install Vitest to run our unit tests. We can install it with:<\/p>\n\n\n\nSetting Up Vitest<\/h2>\n\n\n
npm create vite@latest<\/code>). <\/p>\n\n\n\n