search
HomeWeb Front-endJS TutorialLessons Learned Migrating from React CRA & Jest to Vite & Vitest

Lessons Learned Migrating from React CRA & Jest to Vite & Vitest

This article is for EDOCODE Advent Calendar 2024, published on 16th December 2024.

The previous article was written by Taiji Yamada, a Product Manager at EDOCODE: Automated Email System Using Notion Webhooks and the No-Code Tool "Make" (The article is in Japanese).

Also, please check out the Wano Advent Calendar by our parent group company!

Introduction

Our app, Gojiberry, is a Shopify survey app that helps merchants gather valuable feedback from their customers.

From the very beginning, we’ve built Gojiberry with test-driven development (TDD) to ensure our app is bug-free and that we can confidently release new features without breaking existing functionality. This foundation has allowed us to make large-scale changes, like migrating from Create React App (CRA) to Vite, with minimal disruption.

When CRA was deprecated, and its dependencies became outdated, we decided it was time to upgrade to a modern build tool that would better support our growing app. The large size of our codebase added some complexity, but the switch to Vite proved to be worth the effort.

Our goal was to migrate our two React projects:

  • ? The Survey: Displayed to end-users to collect their responses.
  • ? The Admin Dashboard: Used by merchants to configure surveys and view analytics.

If you're a Shopify store owner looking to gather actionable customer feedback, try out Gojiberry today on the Shopify App Store!

Motivation for the Migration

CRA served us well in the past, but it’s no longer maintained, and its dependencies have become outdated. This posed several challenges:

  • ? Outdated libraries: We couldn’t update to critical libraries like user-events v14, which introduced significant improvements for handling async tests.
  • ? Slow tests: Jest tests were getting slower over time, and we wanted the faster build and test times offered by Vite and Vitest.
  • ⚖️ Inconsistent behavior: Across the two projects in our monorepo, both using the same user-events version, one required wrapping every action with act() while the other didn’t. This inconsistency created confusion and slowed development.
Key Changes in user-events v14

One of the biggest improvements in user-events v14 is the requirement to use await for all interaction methods. This eliminates the need for wrapping actions in await waitFor, making test code cleaner and easier to maintain.

Before (user-events v13):

import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import MyComponent from './MyComponent';

test('updates state on click', async () => {
  render(<mycomponent></mycomponent>);

  userEvent.click(screen.getByRole('button'));

  await waitFor(() => {
    expect(screen.getByText('Updated state')).toBeInTheDocument();
  });
});

After (user-events v14):

import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import MyComponent from './MyComponent';

test('updates state on click', async () => {
  render(<mycomponent></mycomponent>);

  userEvent.click(screen.getByRole('button'));

  await waitFor(() => {
    expect(screen.getByText('Updated state')).toBeInTheDocument();
  });
});

This change simplifies tests by removing the need to explicitly manage state changes with waitFor. Developers no longer need to think about when to include await waitFor, as the library automatically handles it.

The improvements in user-events v14 and Vitest addressed many of these issues, offering a cleaner, faster, and more consistent development experience.

Alternatives Considered

Before choosing Vite, we evaluated Next.js and Remix. While both are powerful frameworks, they required significant changes to our codebase and infrastructure:

  • Next.js and Remix:

    • ? Codebase reorganization: Both frameworks required us to restructure our codebase to fit their conventions, which would have been a time-consuming process.
    • ?️ Infrastructure changes: These frameworks are not Single Page Application (SPA) frameworks, so adopting them would have required updates to our deployment and hosting infrastructure.
    • ⚖️ Overkill for our needs: While they offer great features for server-side rendering and routing, these features were unnecessary for our use case.
  • Why we chose Vite:

    • ? Minimal code changes: Vite required almost no changes to our existing codebase, making the transition straightforward and efficient.
    • ?️ 1-to-1 compatibility with Jest: With Vitest being highly compatible with Jest, we could reuse most of our test code with minimal adjustments.
    • Performance improvements: Vite provided faster build times, and Vitest significantly sped up test execution.

By choosing Vite, we avoided the complexity of adopting a full-fledged framework while reaping the benefits of a modern, lightweight build tool.

Migration Process

We approached the migration systematically since our monorepo contains two separate npm projects. Here’s how we executed the migration:

  1. Start with the smaller project:

    • ?️ Migrating the smaller project first allowed us to identify potential pitfalls without risking the larger project.
  2. Migration steps:

    The process for each project followed these steps:

    • ? Migrate to Vite: Replace CRA with Vite, fix any errors, and ensure the app builds and runs correctly.
    • ? Fix TypeScript errors: Vite introduced stricter TypeScript rules, exposing issues in the codebase. Fixing these made the code more resilient and reduced bad practices.
    • Migrate to Vitest: Transition tests from Jest to Vitest.
    • ? Fix test errors: Address any broken tests caused by differences in how Jest and Vitest handle certain scenarios.
    • ? Upgrade to user-events v14: Update the test library and fix broken tests. While many tests needed manual fixes, most issues stemmed from incorrect test cases, such as not waiting for React state changes when necessary. This was a valuable opportunity to spot and correct errors in our tests.
  3. Repeat for the larger project:

    • ? After successfully migrating the smaller project, we applied the same steps to the larger project.

Challenges Encountered

  • ? Broken tests: Migrating to Vitest and upgrading to user-events v14 caused numerous test failures. However, these failures revealed underlying issues in our test cases, such as missing await calls for React state changes. Fixing these improved the accuracy and reliability of our tests.
  • ?️ TypeScript strictness: Vite’s stricter TypeScript rules exposed problematic patterns in our code. While it required extra effort to fix these errors, the end result was a cleaner and more resilient codebase.

Outcome

The migration from CRA to Vite, along with the transition to Vitest and user-events v14, has delivered substantial improvements to our development workflow:

  • Faster build and test times: After the migration, our test suite now completes in 30% less time, significantly speeding up our CI pipeline.
  • ? Instantaneous hot reload: Vite's hot module replacement (HMR) during development is nearly instantaneous, a vast improvement over CRA, making development more seamless and efficient.
  • ? Improved test clarity and reliability: The upgrade to user-events v14 and Vitest resulted in cleaner and more consistent tests. Many incorrect tests were fixed during the migration, helping us catch hidden bugs and improve overall code quality.
  • ?️ Resilient codebase: Vite’s stricter TypeScript rules exposed several areas for improvement in our code, making the app more robust and reducing the likelihood of bad practices.

The migration has been a game-changer, allowing us to iterate faster while maintaining confidence in our codebase.

Lessons Learned

Here are some takeaways from our experience:

  • ? Start small: Begin with smaller projects to reduce risks and refine the process.
  • Plan for broken tests: Expect some test cases to break and allocate time for fixing them. These failures often reveal deeper issues worth addressing.
  • ?️ Embrace stricter rules: While stricter TypeScript rules and framework differences can initially feel like obstacles, they ultimately lead to a better codebase.
  • ? Evaluate frameworks carefully: Choose tools that align with your existing architecture and goals.

Conclusion

Migrating from CRA to Vite and Vitest has brought significant improvements to our workflow. We now enjoy faster builds, cleaner test code with user-events v14, and a more resilient codebase thanks to stricter TypeScript rules.

One of the key factors that made this transition smoother was our early investment in test-driven development (TDD). With a comprehensive suite of tests in place, we were able to confidently make massive changes without breaking existing functionality.

If you’re considering a similar migration, we hope our experience provides valuable insights to guide your journey.


Tomorrow, 17th December 2024, the article will be Switching from B2C to B2B: a marketers confession by Amee Xu, a Product Marketing Manager at Gojiberry.

At Wano Group, we are hiring! If you are interested, please check out our open positions using the link below:

JOBS | Wano Group

The above is the detailed content of Lessons Learned Migrating from React CRA & Jest to Vite & Vitest. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.