Error: Cannot find module ' in Protractor

cmplfore picture cmplfore · Oct 10, 2016 · Viewed 11.2k times · Source

So I'm new to protractor and trying test using page objects to make the code more manageable. Having some problems with this side of it.

Below is my main spec file called 'example_spec.js'

describe('angularjs homepage', function() {

  var home_page = require('../home_page.js');

  it('should greet the named user', function() {
    home_page.enterFieldValue('Jack Sparrow');
    var getHomePageText = home_page.getDyanmaicText();
    expect(getHomePageText).toBe('Hello Steve!');
  });
});

The next file is the page object called 'home_page.js'

var home_page = function(){

    //Send in a value.
    this.enterFieldValue = function(value){
        element(by.model('youName')).sendKeys(value);
    };

    this.getDyanmaicText = function(){
      return element(by.binding('yourName')).getText();

    };

};

module.exports = new home_page();

The issue is when running this test I get the error below. Even when trying different paths for the file i keep getting the error. Any help would be appreciated.

Failures:
1) angularjs homepage encountered a declaration exception
  Message:
    Error: Cannot find module '../home_page.js'
  Stack:
    Error: Cannot find module '../home_page.js'
        at Function.Module._resolveFilename (module.js:455:15)
        at Function.Module._load (module.js:403:25)
        at Module.require (module.js:483:17)
        at require (internal/module.js:20:19)
        at Suite.<anonymous> (/Users/testuser/dev/example_spec.js:3:19)
        at Object.<anonymous> (/Users/testuser/dev/example_spec.js:1:1)
        at Module._compile (module.js:556:32)

Answer

alecxe picture alecxe · Oct 10, 2016

Not the direct answer to the question, but the general approach to solve the "require" problem in Protractor while importing Page objects or Helper functions.

What we've done was to introduce 2 global helper functions - one for page objects and the other one for helpers. Put this into onPrepare() in your config:

// helper require function to import page objects
global.requirePO = function (relativePath) {
    return require(__dirname + '/../po/' + relativePath + '.po');
};

// helper require function to import helpers
global.requireHelper = function (relativePath) {
    return require(__dirname + '/../helpers/' + relativePath + '.js');
};

Adjust the paths accordingly - __dirname is the place where your config lies in. The provided functions would work for the following structure:

- e2e
  - config
     protractor.conf.js
  - po
     home_page.js
  - helpers
     helpers.js
  - specs
     example_spec.js

Then, you would be able to just have:

var home_page = requirePO('home_page');

inside your spec file.