我开始在我的量角器测试套件中使用来自$http_backend
(1.2.16)的angular-mocks
服务。
我写了以下模拟:
$httpBackend
.when('POST', 'http://localhost:3000/users')
.respond(200, {
"user": {
"id": "5347b31750432d45a5020000",
"name": "foobar",
"email": "foobar@test.org",
"authentication_token": "erqhglzerjaehregalergh"
}
});
......完美无缺。但我也想模拟错误响应,如:
$httpBackend
.when('POST', 'http://localhost:3000/users')
.respond(422, {
'message': 'Validation failed',
'status': 422,
'errors': [
{ 'resource': 'User', 'field': 'email', 'code': 'already_exists' },
{ 'resource': 'User', 'field': 'password', 'code': 'invalid' }
]
}
);
问题:如何定义这两种响应?
我考虑在我的网址中添加选项,例如:
http://localhost:3000/users?test=success
http://localhost:3000/users?test=error
但是,触发该调用的操作在我的测试套件中:
element(page.form.signup).findElement(by.css('button[type=submit]')).click();
...我无法在网址中设置选项。
你还有其他想法吗?
答案 0 :(得分:1)
由于这是两种不同的测试场景(成功和错误),因此在每个测试声明中简单地定义要单独响应的数据是有意义的:
it('Should display error message if validation fails', function () {
$httpBackend
.when('POST', 'http://localhost:3000/users')
.respond(422, {
'message': 'Validation failed',
'status': 422,
'errors': [
{ 'resource': 'User', 'field': 'email', 'code': 'already_exists' },
{ 'resource': 'User', 'field': 'password', 'code': 'invalid' }
]
});
element(page.form.signup).findElement(by.css('button[type=submit]')).click();
$httpBackend.flush();
//check for expected response
});
it('Should respond with user information if validation successful', function () {
$httpBackend
.when('POST', 'http://localhost:3000/users')
.respond(200, {
"user": {
"id": "5347b31750432d45a5020000",
"name": "foobar",
"email": "foobar@test.org",
"authentication_token": "erqhglzerjaehregalergh"
}
});
element(page.form.signup).findElement(by.css('button[type=submit]')).click();
$httpBackend.flush();
//check for expected response
});