2016-12-28 73 views
0

我想在單元測試中獲得/設置「testModel.number」,但似乎無法得到它。當我運行測試我收到此錯誤信息:將構造函數中的參數之一傳遞給單元測試

Error: [$injector:unpr] Unknown provider: testModelProvider <- testModel 

這裏是控制器:

angular.module("TestApp", []) 
    .controller("IndexController", function ($scope, testModel) { 
     $scope.name = "test"; 

     testModel = { 
      number: 0 
     } 

     if (testModel.number === 1) { 
      $scope.name = "test1"; 
     } else { 
      $scope.name = "test2"; 
     } 
    }); 

下面是單元測試:

describe('IndexController', function() { 
    var scope, createController; 

    beforeEach(module("TestApp")); 

    beforeEach(inject(function ($rootScope, $controller, testModel) { 
     scope = $rootScope.$new(); 

     createController = function() { 
      return $controller('IndexController', { 
       '$scope': scope, 
       'testModel': testModel 
      }) 
     } 
    })); 

    it('example test', function() { 
     var controller = createController(); 
     testModel.number = 1; 

     expect(scope.name).toBe('test1'); 
    }); 
}); 

我對單元測試相當陌生,所以任何建議都會很棒!提前致謝!

回答

1

我認爲您需要將testModel對象傳遞給創建控制器的方法。茉莉花不知道如何注入自定義提供程序。

describe('IndexController', function() { 
    var scope, createController; 

    beforeEach(module("TestApp")); 

    beforeEach(inject(function ($rootScope, $controller) { 
     scope = $rootScope.$new(); 

     createController = function (testModel) { 
      return $controller('IndexController', { 
       '$scope': scope, 
       'testModel': testModel 
      }) 
     } 
    })); 

    it('example test', function() { 
     var testModel = { number: 1 }; 
     var controller = createController(testModel); 

     expect(scope.name).toBe('test1'); 
    }); 
}); 

如果你有需要的testModel對象的多個測試,還可以在全球範圍如下定義它:

describe('IndexController', function() { 
    var scope, createController; 
    var testModel = { number: 1 }; 

    beforeEach(module("TestApp")); 

    beforeEach(inject(function ($rootScope, $controller) { 
     scope = $rootScope.$new(); 

     createController = function() { 
      return $controller('IndexController', { 
       '$scope': scope, 
       'testModel': testModel 
      }) 
     } 
    })); 

    it('example test', function() { 

     var controller = createController(); 

     expect(scope.name).toBe('test1'); 
    }); 
}); 
+0

真棒它的工作,感謝給我看這些方法! –

相關問題