【问题标题】:Jasmine testing async angular controller functionJasmine 测试异步角度控制器功能
【发布时间】:2015-03-04 00:59:13
【问题描述】:

首先,这是我第一次尝试在我的应用程序中运行测试。 下面的代码是为了测试一个控制器函数的结果($scope.getActiveClients(),这个函数发出一个 $http 获取请求)返回的对象: $scope.activeClients 在我的测试运行时是未定义的。 到目前为止,我已经尝试了 jasmine 的 2.0 文档中所述的 runs() 和 waitsFor() 以及 done() 函数,但均无济于事,并收到此错误消息:

TypeError: undefined is not a function

 describe 'myController', ->
   beforeEach module('myApp')
   $controller = undefined
   beforeEach inject((_$controller_) -> 
     $controller = _$controller_
     return
  )
  describe '$scope.activeClients', ->
    it 'gets all active clients', ->
      $scope = {}
      controller = $controller('myController', $scope: $scope)
      $scope.getActiveClients()
      expect($scope.activeClients).toEqual xxx
      return
    return
  return

任何指针将不胜感激

【问题讨论】:

    标签: angularjs coffeescript jasmine


    【解决方案1】:

    您需要通过 $httpBackend 模拟 $http 调用,然后才能获取 http 调用并测试异步调用。 我不知道coffescript,但可以用js告诉你。

    describe('myController', function(){
     var $scope, controllerService, httpMock;
     beforeEach(module('myApp'));
     beforeEach(inject(function ($rootScope, $controller, $httpBackend) {
        $scope = $rootScope.$new();
        controllerService = $controller;
        httpMock = $httpBackend;
     }));
    
     it("gets all active clients", function () {
       //mock http calls
       httpMock.expectGET("/getActiveClients").respond({data: 'clientTestData'});
       ctrl = controllerService('myController', {$scope: $scope});
       $scope.getActiveClients();
       httpMock.flush();
       expect($scope.activeClients).toEqual xxx
     });
    });
    

    【讨论】:

    • 虽然您的回答不是 100% 准确,但它指出了我正确的方向,谢谢。
    猜你喜欢
    • 2021-01-18
    • 1970-01-01
    • 2014-08-21
    • 1970-01-01
    • 2015-02-15
    • 2015-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多