如何在我的案例中对函数进行单元测试

时间:2015-10-19 20:16:46

标签: angularjs unit-testing karma-runner

我正在尝试对失败的http请求进行单元测试。我有类似

的东西

JS控制器

myFactory.getName(url)
     .then(function(returnData) {                        
         console.log(returnData)  //works
      }, function() {                                          //not cover
          console.log('error')  //never get called             //not cover
          $timeout(function() {                                //not cover
             //do stuff                                        //not cover
              }, 100);                                         //not cover
      });

我的工厂

factory.getName = function(url) {
        return $http.get(url);
};

单元测试

  beforeEach(module('muApp'));
    beforeEach(inject(function (_$controller_, _$httpBackend_, _$rootScope_, _$timeout_, myFactory_) {
        scope        = _$rootScope_.$new();
        $httpBackend = _$httpBackend_;
        $timeout     = _$timeout_;
        $rootScope   = _$rootScope_;
        myFactory = _$myFactory_;

        myCtrl = _$controller_('myCtrl', {
            '$scope': scope
        });

        $httpBackend.expectGET('/api/request/aaa').respond(404);
    }));

describe('test' , function(){
     it('should show error if request fail', function() {
            myFactory.getName('/api/request/aaa');
            $httpBackend.flush();
     });

    //Will show error but still won't cover the call back function
     it('should show error if request fail', function() {
            myFactory.getName('/api/request/aaa').then(function() {

            }, function(){
               console.log('error')  // this will show in my karma
            });
            $httpBackend.flush();
     });

})

我想介绍一下回调错误功能,但不知道这里有什么问题。谢谢你的帮助!

0 个答案:

没有答案