Search code examples
javascriptcypresses6-modules

how to import JS function inside cypress.config.js


I have an email.js file which has a function called email_func and I want to call that function inside the after:run block inside cypress.config.js file.

However, I am getting the following error when I try to require() it.

Your configFile is invalid: D:\Cypress-automation\cypress-automation\cypress.config.js
It threw an error when required, check the stack trace below:

ReferenceError: require is not defined in ES module scope, you can use import instead
This file is being treated as an ES module because it has a '.js' file extension and 'D:\Cypress-automation\cypress-automation\package.json' contains "type": "module".
To treat it as a CommonJS script, rename it to use the '.cjs' file extension.

In email.js file I did export as follows

const email_var = new emailClass();
module.exports = email_var;

and in cypress.config.js I am trying to do import like this but no luck

const email_var = require('./cypress/support/email');

Solution

  • After much research,following worked for me

    in email.js exported variable in this manner

     exports.email_var = new emailClass();
    

    in cypress.config.js imported in this manner

    const { email_var } = require('./cypress/support/email.js');
    

    Now, I can call my function as follows

    email_var.email_function(results);