cypressenvironmentnrwl-nxweb-component-tester

NX component testing with cypress error process is not defined


I am using NX 14.5.1 and cypress 10.2.0. When I run cypress component testing for "libs/ui" always got "Process not defined" error. In the component call ".env" like this:

import consola from 'consola'

export const logger = consola.create({
  level: process.env.NX_ENV_NAME === 'production' ? 0 : 5
})

This is my "cypress.config.ts":

import { defineConfig } from 'cypress';
import { nxComponentTestingPreset } from '@nrwl/react/plugins/component-testing';

export default defineConfig({
  component: { 
     ...nxComponentTestingPreset(__dirname)
  }
})

And the error is like this: process is not defined

ReferenceError
The following error originated from your test code, not from Cypress.

  > process is not defined

When Cypress detects uncaught errors originating from your test code it will automatically fail the current test.

Cypress could not associate this error to any specific test.

We dynamically generated a new test to display this failure.

I think Cypress doesn't recognize my ".env". How do I pass my ".env" when I run component testing?


Solution

  • I think the basic problem is the app is server-side-rendered. The server compiles in Node where process is available, but the component test runs in the browser where process isn't valid.

    This is the way you might tackle it:

    In cypress.config.js load the process.env you need into Cypress.env

    import { defineConfig } from 'cypress';
    import { nxComponentTestingPreset } from '@nrwl/react/plugins/component-testing';
    
    const  setupNodeEvents = (on, config) => {
      config.env = {
        ...config.env,
        ...process.env.NX_ENV_NAME,
      }
      return config  
    }
    
    export default defineConfig({
      component: { 
         ...nxComponentTestingPreset(__dirname),
         setupNodeEvents
      }
    })
    

    In the component, check where the component is being run from.

    import consola from 'consola'
    
    const envName = window && window.Cypress 
      ? window.Cypress.env('NX_ENV_NAME')     // running in browser, take Cypress.env
      : process.env.NX_ENV_NAME;              // running SSR, take process.env
    
    const level = envName === 'production' ? 0 : 5;
    
    export const logger = consola.create({
      level
    })
    

    This is messy but removes the restriction on running SSR code in a browser environment.