0

I'm using Ember CLI's http-mock feature to mock REST API endpoints, but I'd like to use it in multiple Ember CLI applications. I thought an addon would be a great solution to this, but I can't seem to get it to work. Does Ember Addon support http-mock?

Here's what I did.

Created an add on

$ ember addon my-http-mock

Then I created a simple test endpoint in the addon

$ ember g http-mock users

After publishing it to my github repository, I imported it into an Ember CLI project like this in package.json

"dependencies": {
    "my-http-mock": "git://github.com/git-username/my-http-mock"
}

After npm installing it, I ran my app, but going to http://localhost:4200/api/users doesn't go to the API endpoint, and instead tries to load the Ember app.

Is there any way to use http-mock in multiple applications?

1 Answer 1

3

You'll need to have your addon implement the serverMiddleware and you can add middleware, or routes, to the http-mock running in the consuming ember-cli application.

Advanced Addon customization in ember-cli docs

That hook get's passed a config object that has the express app instance on it at config.app. You can then add whatever you'd like to do. If you're using the generated http-mock in the addon, it'd look something like this

{
  name: 'my-http-mock',
  serverMiddleware: function(config) {
    // To require ALL mocks from your addon
    var server = require('./server');
    server(config.app);

    // To require individual mocks
    var users = require('./server/mocks/users');
    users(config.app);
  }
}

This is untested code but should work. The require all mocks one could possibly conflict in a weird way because it adds the bodyparser middleware and connect-restreamer and it probably already has that included if your app already has those from it's local http-mock. Try it out though! :)

note: This answer is in reference to using ember-cli 0.1.2

Sign up to request clarification or add additional context in comments.

2 Comments

This works perfectly. Even the 'ALL mocks' option works and does not conflict with the local http-mock, although if both the addon and the local http-mock have the same endpoint, the local one will win. One thing that tripped me up is that the local http-mock will return the API response regardless of what the Accept request header is, while the addon http-mock will not respond if the Accept request header is 'text/html'. So make sure you don't test the addon API by typing the URL in the browser address bar, b/c it will make you think the addon is not working.
Glad you figured it out Johnny!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.