title: Using require with relative paths
body: <p>We have a rather big set of end-to-end tests on Protractor. We are following the Page Object pattern which helps us to keep our tests clean and modular. We also have a set of helper functions which help us to follow the <a href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself" rel="noreferrer">DRY principle</a>.</p>
  
  <p><strong>The Problem:</strong> </p>
  
  <p>A single spec may require multiple page objects and helper modules. For instance:</p>
  
  <pre><code>"use strict";
  
  var helpers = require("./../../helpers/helpers.js");
  var localStoragePage = require("./../../helpers/localStorage.js");
  var sessionStoragePage = require("./../../helpers/sessionStorage.js");
  
  var loginPage = require("./../../po/login.po.js");
  var headerPage = require("./../../po/header.po.js");
  var queuePage = require("./../../po/queue.po.js");
  
  describe("Login functionality", function () {
  
      beforeEach(function () {
          browser.get("/#login");
  
          localStoragePage.clear();
      });
  
      // ...
  
  });
  </code></pre>
  
  <p>You can see that we have that directory traversal in every require statement: <code>./../..</code>. This is because we have a <code>specs</code> directory where we keep the specs and multiple directories inside grouped by application functionality under test.</p>
  
  <p><strong>The Question:</strong></p>
  
  <p>What is the canonical way to approach the relative path problem in Protractor?</p>
  
  <p>In other words, we'd like to avoid traversing the tree, going up to import modules. It would be much cleaner to go down from the base application directory instead.</p>
  
  <hr>
  
  <p><strong>Attempts and thoughts:</strong></p>
  
  <p>There is a great article about approaching this problem: <a href="https://gist.github.com/branneman/8048520" rel="noreferrer">Better local require() paths for Node.js</a>, but I'm not sure which of the options is a recommended one when developing tests with Protractor.</p>
  
  <p>We've also tried to use <a href="https://nodejs.org/api/modules.html#modules_accessing_the_main_module" rel="noreferrer"><code>require.main</code></a> to construct the path, but it points to the <code>node_modules/protractor</code> directory instead of our application directory. </p>