【发布时间】:2015-04-14 18:26:18
【问题描述】:
我所有的 UNIT 测试,而不是 E2E 测试,执行显式 rootScope.digest() 或 httpBackend.flush() 来刷新异步回调,都会遇到错误:
How to avoid the 'Error: Unexpected request: GET'
No more request expected
我认为这是因为 httpBackend 调用了 ui-router 模板。我不知道它为什么要这样做。我不是要这个。我只希望它调用我的模拟 json 服务。
这个错误迫使我在每个 it() 块中都有以下语句:
$httpBackend.whenGET(/\.html$/).respond('');
一定有更整洁的方法。
特别是如果测试首先没有使用 $httpBackend:
it('should return the list of searched users', function() {
// Always use this statement so as to avoid the error from the $http service making a request to the application main page
$httpBackend.whenGET(/\.html$/).respond('');
var users = null;
UserService.search('TOTO', 1, 10, 'asc', function(data) {
users = data.content;
});
$rootScope.$digest();
expect(users).toEqual(RESTService.allUsers.content);
});
测试通过了,但它看起来很老套。或者是noobish :-)
编辑:另一个测试:
it('should return the list of users', function () {
// Always use this statement so as to avoid the error from the $http service making a request to the application main page
$httpBackend.whenGET(/\.html$/).respond('');
// Create a mock request and response
$httpBackend.expectGET(ENV.NITRO_PROJECT_REST_URL + '/users/1').respond(mockedUser);
// Exercise the service
var user = null;
RESTService.User.get({userId: 1}).$promise.then(function(data) {
user = data;
});
// Synchronise
$httpBackend.flush();
// Check for the callback data
expect(user.firstname).toEqual(mockedUser.firstname);
expect(user.lastname).toEqual(mockedUser.lastname);
});
【问题讨论】:
-
我认为测试绝对是在这里拨打
$http。为什么不实际expect调用您的用户 API 端点? -
是的,它确实发出了一个 http 请求。但是我的很多测试也是如此。我没明白你的问题。我将编辑问题以添加另一个展示相同解决方法的测试。