如何使用Jasmine对$ scope.broadcast,$ scope。$进行unit testing

我是AngularJs / NodeJs世界的新手,所以如果这是一个基本的问题,请原谅。

所以简而言之,我有两个控制器,第一个控制器$broadcast一个“Id”,第二个控制器通过$on获取该Id,然后将该Id传递给一个中间service ,这会产生一个$http ajax调用,并返回一个Book对象。

如何使用Jasmine对$ scope.broadcast,$ scope。$进行unit testing

firstCtrl

 .controller('firstCtrl', function($scope, ...){ $scope.selectGridRow = function() { if($scope.selectedRows[0].total !=0) $scope.$broadcast('id', $scope.selectedRows[0].id);//Just single plain ID }; }); 

secondCtrl

 .controller('secondCtrl', function($scope, bookService) { $scope.$on('id', function(event, id) { bookService.getBookDetail(id).then(function(d) { $scope.book = d.book; }); }); }); 

预计Json obj

 var arr = "book" : [ { "id" : "1", "name" : "Tomcat", "edition" : "9.1" } ] 

让我知道是否有人要我发布第二个控制器使用的$http服务。

预期的行为

所以从理论上来说,我想testing每种可能的情况,但是像下面这样的东西可以花费在:

 expect(scope.book).toEqual(arr); expect(scope.book).not.toEqual(undefined); 

感谢大家!

首先,您应该在$rootScope进行广播,然后您可以在$scope上接收。 现在进行testing。 我假设你想通过bookService$http包含真正的请求到您的API。 这可以被嘲笑,但我会专注于真正的呼叫。 让我知道如果你需要嘲笑的一个。

在实际testing之前,您需要进行一些注射/实例化:

  • 初始化您的应用程序
  • 注入$controller$rootScope$httpBackendbookService
  • 为firstController和SecondController创build范围并将其存储在一个variables中
  • bookService$httpBackend存储在variables中
  • 实例化控制器并存储它们

然后在实际testing中,您必须告诉$httpBackendcaching请求书籍(或书籍)时$httpBackend什么。 构build$httpBackend.whenGET("/api/books/1").passThrough(); 将传递URL "/api/books/1"到服务器的请求。 接下来,您必须在firstScope上设置属性selectedRows ,以便在第一个firstScope实现函数selectGridRow中的firstCtrl

现在你可以调用函数selectGridRow来触发广播和API调用。 但是你必须把它包装在runs函数中,所以Jasmine认为这是一个asynchronous调用,并等待它完成。 waitsFor调用中定义了“等待”。 它将等待,直到它得到一本书,它等待最多5000毫秒,然后testing将被标记为失败。

最后一步是检查预期的结果。 我们不必检查undefined ,因为testing不会到达这里。 该检查必须再次包装runs调用,所以它执行后成功'waitsFor'。

以下是完整的代码:

 describe("Broadcast between controllers", function () { beforeEach(module('app')); //app initialization var firstScope; var secondScope; var bookService; var $httpBackend; var firstController; var secondController; beforeEach(inject(function ($controller, $rootScope, _bookService_, _$httpBackend_) { firstScope = $rootScope.$new(); secondScope = $rootScope.$new(); bookService = _bookService_; $httpBackend = _$httpBackend_; firstController = $controller('firstCtrl', { $scope: firstScope }); secondController = $controller('secondCtrl', { $scope: firstScope, bookService: bookService }); })); it("should work", function () { $httpBackend.whenGET("/api/books/1").passThrough(); firstScope.selectedRows = [{ id: 1, total: 1000 }]; secondScope.book = null; runs(function () { firstScope.selectGridRow(); }); waitsFor(function () { return secondScope.book != null; }, "Data not received in expected time", 5000); runs(function () { expect(secondScope.book[0].id).toEqual(1); }); }); });