2

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'

Alapan Das
  • 17,144
  • 3
  • 29
  • 52

1 Answers1

0

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']

})
Fody
  • 23,754
  • 3
  • 20
  • 37