0

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');

2 Answers2

3

There's almost two languages when it comes to javascript modules, the older cjs using require() and the newer es modules.

Since you have "type": "module" in package.json, you are opting for the latter.

Therefore, cypress.config.js will already have

import { defineConfig }  from 'cypress'

export default defineConfig({
  ...

You need to use import for email.js

import { defineConfig }  from 'cypress'
import email_var from './cypress/support/email.js'

export default defineConfig({
  ...

Plus you need to export in the es-modules style

const email_var = new emailClass();
// module.exports = email_var;
export default email_var;

For more general discussion, see Why is 'type: module' in package.json file?

user16695029
  • 3,365
  • 5
  • 21
  • I have tried these steps but still getting the same error, in my package.json - I did not had "type": "module", but I went ahead and added that and in email.js I did export as below const email_var = new emailClass(); export default email_var; and did try to import that in cypress.config.js as follows import email_var from './cypress/support/email.js' Do I need to do anything differently ? please suggest. – Johnson Kandul Feb 27 '23 at 12:39
0

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);