我有以下控制器(请注意,在实例化时我对 进行了显式调用$scope.getNotifications()
):
bla.controller("myctrl", [
"$scope", "$http", "configs", function ($scope, $http, configs) {
$scope.getNotifications = function () {
$http.get("bla/blabla").success(function (data) {
});
};
$scope.removeNotification = function (notification) {
var index = $scope.allNotifications.indexOf(notification);
$scope.allNotifications.splice(index, 1);
};
$scope.getNotifications();
}
]);
然后我做了一些单元测试(注意控制器在每个之前被实例化):
describe("blaController", function () {
var scope, $httpBackend;
beforeEach(module('bla'));
beforeEach(inject(function ($controller, $rootScope, _$httpBackend_) {
scope = $rootScope.$new();
$httpBackend = _$httpBackend_;
$controller('blaCtrl', { $scope: scope });
}));
afterEach(function(){
//assert
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
it("should get all notifications from server when instantiated", function () {
//arrange
$httpBackend.expectGET("api/v1/notifications").respond(200, {});
$httpBackend.flush();
//act - done implicitly when controller is instantiated
});
it("should store all notifications from server on the client when success call to server", function () {
//arrange
$httpBackend.whenGET("api/v1/notifications").respond(200, [{ a: 1, b: 2 }, { c: 3, d: 4 }]);
$httpBackend.flush();
//act - done implicitly when controller is instantiated
//assert
expect(scope.allNotifications).toEqual([{ a: 1, b: 2 }, { c: 3, d: 4 }]);
});
到目前为止一切都很好。所有测试通过。但是,当我添加一个不需要任何 HTTP 调用的新测试(见下文)时,它会失败,因为afterEach()
它会验证预期,但removeNotification()
. 这是来自业力的错误消息:
PhantomJS 1.9.7 (Windows 8) notificationCenterController removeNotification 应该从列表中删除给定的通知 FAILED 错误:意外的请求:GET api/v1/notifications 没有更多的请求预期
it("should remove the given notification from the list", function () {
//arrange
var targetObj = { a: 2 };
scope.allNotifications = [{ a: 1 }, targetObj, { a: 3 }];
//act
scope.removeNotification(targetObj);
//assert
expect(scope.allNotifications).toEqual([{ a: 1 }, { a: 3 }]);
});
我的大部分测试都有 http 调用,因此将验证放在 afterEach 中是有意义的。我想知道还有什么其他选择可以避免在 N-1 测试中复制粘贴 afterEach 主体。有没有办法告诉$httpBackend
忽略任何电话?