Using Config to Define Absolute Paths in Cypress

Certainly both relative path and absolute path (import/require) has its pros and cons — but personally, I prefer to use absolute path as it offers more readability and refactor-ability (i.e. moving file to different folder structure)

Wir
Nerd For Tech
3 min readMay 21, 2021

--

For as long as I remember, I’ve never have to deal much with import or require while coding (specifically in C#), because it’s certainly using namespace import. The namespace itself reflects the folder structure or path of the file to be used (or imported in this case).

If you’ve been coding in Cypress and TypeScript to create automation tests, chances are you use design pattern. I use Page Object Model (POM) design pattern to define elements and element actions (i.e. click() and type()) in a page. As the codebase grows, I realised I was using more and more of relative path to import or require a POM or a fixture file. Sometimes, several POMs and fixtures are required in a single describe because of connected test flows and assertions.

It should be easy though by using '~/'. But I think JavaScript/TypeScript does not behave that way as it will give you an error.

Cannot find module ‘~/path/to/POM’ or its corresponding type declarations.

Several blog posts I read about absolute path in Cypress are indeed outdated. The best one with solutions is in GitHub. But, the first 2 solutions (using @cypress/webpack-preprocessor and CypressFileKindPlugin) didn’t work for me. Even if it works, the solutions are too complicated to my liking, especially if using webpack-preprocessor because I have to install 4 additional dependencies (@babel/core, @babel/preset-env, babel-loader, and webpack) which I might not be using them at all.

The 3rd solution by marklawlor is not only working, but also the simplest one. Many thanks to him! 😄

So, here is the recap of what I did using his solution in combination with flybayer

  • npm install --save-dev tsconfig-paths
  • Create a new file in root folder of the project tsconfig.json
tsconfig.json setup
tsconfig.json
  • Update tsconfig.json file inside cypress folder by adding extends and baseUrl
cypress/tsconfig.json
  • Update index.ts of the plugin file
cypress/plugins/index.ts

And... voila! You can then use absolute path import and require, using the paths specified in the root tsconfig file.

cyprsss/integration/login.spec.ts

--

--

Wir
Nerd For Tech

Quality enthusiast | A curious person, thinker. and persistent, but sometimes a stubborn person. A learner, dedicated to growth.