简体   繁体   English

使用ember-cli-mirage测试错误响应

[英]Testing error responses with ember-cli-mirage

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. 我正在阅读ember-cli-mirage的有关创建模拟响应的文档,但无法弄清楚如何针对完全相同的请求测试错误响应。 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? 海市rage楼如何建议这样做?

Within tests, the route handlers defined in config.js are loaded, but since you have access to server you can actually overwrite those handlers. 在测试中,将加载config.js中定义的路由处理程序,但是由于您有权访问server ,因此实际上可以覆盖这些处理程序。

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. 还有一个API的PR ,它允许您编写瞬态路由处理程序,这对于测试应用程序是否可以从错误中恢复非常有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM