ember.jsember-cliember-cli-addons

access dummy project's root path from ember cli addon in tests


Scenario: I'd like to know the proper way to access the root path of a project that's consuming the addon - that also works while testing...

e.g., the addon:

// ember-cli-myaddon/index.js
{

  ...

  contentFor(name) {
    if (name ==='body') {
      var filePath = path.join(this.app.project.root, 'app/some-file.html')
      var file = fs.readFileSync(filePath);

      return [file];
    }
  },

  ...

}

^ that works when using the addon inside an actual project.

However when I run tests for the addon, this.app.project.root is ~/ember-cli-myaddon/app/some-file.html

When I expect (need) it to be ~/ember-cli-myaddon/tests/dummy/app/some-file.html


Solution

  • After some ember addon digging I came across a great sol'n used in ember-cli-mirage, https://github.com/samselikoff/ember-cli-mirage/blob/master/ember-cli-build.js

    The gist is that the file path is specified in the addon's ember-cli-build.js and the addon reads from that property, defaulting to this.app.project.root when blank.

    e.g.

    // ember-cli-myaddon/index.js
    
    // added this
    included: function() {
      this.addonPath = this.app.options['myaddon']['directory'] || 'app';
    },
    
    // modified filePath
    contentFor(name) {
      if (name ==='body') {
        var filePath = path.join(this.app.project.root, this.addonPath, 'some-file.html');
        var file = fs.readFileSync(filePath);
    
        return [file];
      }
    }
    

    and then inside the addon's ember-cli-build.js file we specify the dummy app's directory:

    // ember-cli-build.js
    
      /* global require, module */
    
      var path = require('path');
      var EmberApp = require('ember-cli/lib/broccoli/ember-addon');
    
      module.exports = function(defaults) {
        var app = new EmberApp(defaults, {
          'myaddon': {
            directory: path.join('tests', 'dummy')
          }
        });
    
        return app.toTree();
      };
    

    And now, addon tests look for some-file.html at:
    ember-cli-myaddon/tests/dummy/app/some-file.html

    and inside a real project, some-file.html is looked for at:
    your-project/app/some-file.html

    Plus you get the bonus of allowing the user to configure the path of the file in their ember-cli-build.js file! win/win/win