How to compile Cypress e2e tests/files using Vite?

Viewed 299

By default, Cypress compiles e2e tests with a built-in webpack config, which used to be fine because Vue-CLI also used Webpack; however, now that I've upgraded to Vue 3 and Vite, no webpack.

I have two options:

  1. Revive the old webpack config for my Vue 2 project and update it for Vue 3 just to run Cypress' e2e tests.
  2. Figure out how to tell Cypress to compile the app with Vite and not Webpack

I can't figure out #2, and I don't want to do #1 because having two different compilation methods sounds like a really bad future headache.

So far, I have this for my Cypress config:

import { devServer } from '@cypress/vite-dev-server'
import { defineConfig } from 'cypress'
import * as path from 'path'

export default defineConfig({
  chromeWebSecurity: false,
  projectId: '5kusbh',
  requestTimeout: 10000,
  responseTimeout: 60000,
  viewportHeight: 1080,
  viewportWidth: 1920,

  e2e: {
    baseUrl: 'http://localhost:8080',
    setupNodeEvents (on, config) {
      on('dev-server:start', (options) => {
        return devServer({
          ...options,
          viteConfig: {
            configFile: path.resolve(__dirname, 'vite.config.ts'),
          },
        })
      })

      return config
    },
    specPattern: 'cypress/e2e/**/**.spec.js',
  },
})

However, when I run Cypress, I get a webpack compilation error, which is telling me Vite is not compiling the application for Cypress.

Note Otherwise, my application is working great - I just can't run Cypress, and we have hundreds of unit, integration, and e2e tests written in Cypress.

TL;DR; I need help configuring Cypress to use my app's Vite config to compile its e2e tests and run it's dev server.

EDIT: I removed my config to see how it'd run just hitting localhost, but Cypress must be trying to compile my code, because it's struggling with the Vite env variable syntax, import.meta.env.[insert key name here] in non-Cypress JavaScript files because it's not process.env...

1 Answers

For e2e tests, the execution of tests is separate from running the app and you access the app using cy.visit(). @cypress/vite-dev-server was for running component tests prior to cypress 10. But with cypress-vite you can also compile e2e tests using vite and use the same configuration as your app, so you don't need to config the webpack anymore.

Related