Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

import module relative to source root directory in Cypress tests

Tags:

cypress

vite

In my app that's build with Vite I can import modules relative to the source root directory with

import { randomId } from '@/utils/string-utils'

This works because in my vite.config.js I've defined this alias

resolve: {
  alias: {
    '@': path.resolve(__dirname, "./src")
  }
}

But Cypress doesn't know anything about this, so if I want to import the module above in a Cypress file, I have to use something like

import { randomId } from '../../../../src/utils/string-utils'

This is tedious and error-prone, because if the Cypress directory structure changed, the import may no longer work. Is it possible to define something similar to the @ alias that will work in Cypress?

like image 309
Dónal Avatar asked Oct 27 '25 10:10

Dónal


1 Answers

To do this, you need to create a tsconfig.json file in your Cypress directory and configure the baseUrl and paths options. see below

// cypress/tsconfig.json
{
  "compilerOptions": {
    "baseUrl": "../src", // Set the base directory for resolving modules
    "paths": {
      "@/*": ["*"] // Define aliases here
    }
  },
  "include": ["**/*.ts"]
}

then you can use it below

// cypress/integration/test-file.ts
import { randomId } from '@/utils/string-utils'; // Use the alias here

if your project is in Javascript

you can create a custom alias for importing modules in Cypress by configuring the Webpack bundler used by Cypress. To set up an alias, you can use the webpack.config.js file within your Cypress directory.

Create a webpack.config.js file in your Cypress directory ( at cypress/webpack.config.js) .

In the webpack.config.js file, configure the aliases by defining a resolve section in the Webpack configuration. You can set up an alias that points to your project's source directory. For example:

// cypress/weboack.config.js
const path = require('path');

module.exports = (on, config) => {
  config.resolve.alias = {
    '@': path.resolve(__dirname, '../src'), // Adjust the path as needed
  };

  // Other configurations...

  return config;
};

usage

like image 196
Sam Avatar answered Oct 29 '25 06:10

Sam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!