Cypress | require() function does not work when variable is passed

Viewed 521

Please help me why this is not working

// Does not work when varialbe pass in require()
var fileName =
  '/Users/ashdiksh/Documents/Automation/CypressTest/cypress/integration/common/pageObjects/cypressDemo.js'
var fileObj = require(fileName)
cy.log(fileObj.elements.web.email)
  // Works fine when path is hardcoded
  var fileObj = require('/Users/ashdiksh/Documents/Automation/CypressTest/cypress/integration/common/pageObjects/cypressDemo.js');
  cy.log(fileObj.elements.web.email);

Error received:

Cannot find module '/Users/ashdiksh/Documents/Automation/CypressTest/cypress/integration/common/pageObjects/cypressDemo.js'

1 Answers

I think you need to involve the webpack compilation process to get it to work, but that's a bit of a pain to do.

Try adding an index.js to your /cypress/integration/common/pageObjects folder.

/cypress/integration/common/pageObjects/index.js

module.exports = {
  pageObject1: require('./pageObject1'),
  pageObject2: require('./pageObject2')
}

Then in the test

const pageObjects = require('./common/pageObjects')  // load the index.js
                                                     // relative to /cypress/integration

it('uses a dynamic pageObject', () => {

  const pageObject = pageObjects['pageObject1']

})
Related