如何测试此Angular控制器?

时间:2016-06-09 06:55:09

标签: javascript angularjs unit-testing karma-jasmine

我发现了Karma伟大的世界,我想问你一个关于我想测试的控制器的简单问题。这是:

angular.module('app', ['ngSanitize'])
.controller('MyController', ['$scope', '$http', function ($scope, $http) {
    $scope.myCtrlData = '';

    $http.get('../../data/file.json').then(function (res) {
    $scope.myCtrlData = res.data.ctrlData;
  });
}]);

它只是向$scope.myCtrlData提供本地json文件内容。

我开始写一个快速测试,但是在运行时我卡住了。

describe('Test : MyController', function() {
  var scope, httpBackend, make;

  beforeEach(module('ngSanitize'));
  beforeEach(module('app'));
  beforeEach(inject(function($rootScope, $controller, $httpBackend){
    httpBackend = $httpBackend;
    scope = $rootScope.$new();

    httpBackend.whenGET('../../data/file.json')
    .respond(200, {
        'data': { 'ctrlData': 'Yeah' }
    });

    make = $controller('MyController', { '$scope': scope });

  }));

  it('should get the data', function() {
    httpBackend.flush();
    expect(scope.myCtrlData).toBeDefined();
    expect(scope.myCtrlData).toEqual('Yeah');
  });
});

结果我在这个日志中失败了:

PhantomJS 2.1.1 (Mac OS X 0.0.0) BioController should get the data FAILED
    Expected undefined to equal 'Yeah'.
/Users/toto/Projects/awesomeproject/tests/views/yeah/test.js:32:30
PhantomJS 2.1.1 (Mac OS X 0.0.0): Executed 1 of 1 (1 FAILED) (0 secs / 0.01 secsPhantomJS 2.1.1 (Mac OS X 0.0.0): Executed 1 of 1 (1 FAILED) ERROR (0.002 secs / 0.01 secs)

请你帮我弄清楚我做错了什么?

非常感谢你的宝贵帮助: - )

1 个答案:

答案 0 :(得分:0)

您需要实例化控制器。

make = $controller('MyController', { '$scope': scope });

$controller('MyController', { '$scope': scope });

此外,

可以修改你的代码吗

 it('should get the data', function() { 
    httpBackend.whenGET('../../data/file.json')
    .respond(200, {
        'data': { 'ctrlData': 'Yeah' }
    });
    expect(scope.myCtrlData).toBeDefined();
    expect(scope.myCtrlData).toEqual('Yeah');
    httpBackend.flush();
  });

从beforeEach中删除httpBackend并检查