AngularJS单元测试 - 未定义不是一个函数

时间:2015-02-26 23:44:40

标签: javascript angularjs unit-testing jasmine karma-runner

我正在尝试学习如何在角度内进行单元测试。单元测试我的控制器,然后开始我的服务。

我已经开始进行基本测试了。

控制器代码:

angular.module('app')
  .controller('TestCtrl', function ($rootScope,$scope,fileLoader,ngProgress) {
 $scope.test= [];
    $scope.init = function(){
      fileLoader.getFile("test")
        .then(function(res){
          //Success
          console.log(res);
          $scope.test= res;
        }, function(err){
          //Error
        });

      ngProgress.complete();
    }

    $scope.init();
$scope.title = "Test";
  });

测试代码:

describe('Controller: TestCtrl', function () {

  // load the controller's module
  beforeEach(module('app'));

  var TestCtrl,
    scope,test;
  test = {};
  test.getFile = function(name) {
    return [
      {
        "id": 0,
        "name": "Test",
        "imgName": "Test.png"
      },
      {
        "id": 1,
        "name": "Test1",
        "imgName": "Test1.png"
      }];
  };


  // Initialize the controller and a mock scope
  beforeEach(inject(function ($controller, $rootScope) {
    scope = $rootScope.$new();
    TestCtrl= $controller('TestCtrl', {
      $scope: scope,
      fileLoader : test
    });
  }));

  it('should have the correct title', function () {
    expect(scope.title).toBe("Test");
  });
});

我无法理解为什么会收到以下错误:

  

TypeError:' undefined'不是一个功能(评估   ' fileLoader.getFile("测试&#34)             .then')undefined

一旦解决了这个问题,我可以把所有的嘲笑都放在一个单独的文件中,例如我的fileLoader模拟并以这种方式注入它?

我不明白我是如何注射的,但尚未定义。

由于

1 个答案:

答案 0 :(得分:3)

  

我无法理解为什么会收到以下错误:

你定义了

fileLoader.getFile("test")
   .then(function(res){

所以getFile()应该返回一个可以解析的promise,但是你返回一个包含两个对象的简单数组

 test.getFile = function(name) {
   return [
   {
    "id": 0,
    "name": "Test",
    "imgName": "Test.png"
   },
   {
    "id": 1,
    "name": "Test1",
    "imgName": "Test1.png"
   }]

重构一边。使用延迟或处理数组结果。