Testing error responses with ember-cli-mirage

本小妞迷上赌 提交于 2019-12-24 01:54:23

问题


I'm reading through ember-cli-mirage's docs about creating mock responses but can't figure out how to test error responses for the exact same request. For example:

test("I can view the users", function() {
  var users = server.createList('user', 3);

  visit('/users');

  andThen(function() {
    equal( find('li').length, 3 );
    equal( find('li:first').text(), users[0].name );
  });
});

test("I can view the error if viewing the users returns an error", function() {
  // somehow set up an error response (?)   

  visit('/users');

  andThen(function() {
    equal( find('#error').length, 1 );
  });
});

It looks like the only way to form the response is in the route

this.get('/users', function(db, request) {

    if (something based on the request, i guess?) {
      return new Mirage.Response(500, {}, {message: 'Oops! Something bad happenned. :('});
    } else {
        return db.users.insert([
            {name: 'Zelda', age: 142},
            {name: 'Epona', age: 58},
        ]);
    }
});

How does mirage recommend going about doing this?


回答1:


Within tests, the route handlers defined in config.js are loaded, but since you have access to server you can actually overwrite those handlers.

What I do in this situation is just create an ad-hoc route handler for the error state:

test("I can view the error if viewing the users returns an error", function() {
  server.get('/users', {errors: ['there was an error']}, 404);

  visit('/users');

  andThen(function() {
    equal( find('#error').length, 1 );
  });
});

Since the server is reinstantiated for each test, this handler won't exist in other tests.

There's also a PR for an API that would allow you to write up transient route handlers, which would be useful for testing that your application could recover from an error.



来源:https://stackoverflow.com/questions/32997349/testing-error-responses-with-ember-cli-mirage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!