问题
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