我所有执行显式 rootScope.digest() 或 httpBackend.flush() 来刷新异步回调的 UNIT 测试(而不是 E2E 测试)都会遇到错误:
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);
});
测试通过了,但看起来很黑客。或者菜鸟:-)
编辑:另一个测试:
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);
});