简体   繁体   English

我该如何测试这个Angular控制器?

[英]How can I test this Angular controller?

I'm discovering Karma great world and I wanted to ask you a simple question about a controller I want to test. 我正在发现Karma伟大的世界,我想问你一个关于我想测试的控制器的简单问题。 Here it is : 这里是 :

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;
  });
}]);

It simply feed $scope.myCtrlData with a local json file content. 它只是用本地json文件内容提供$scope.myCtrlData

I started to write a quick test but I am stuck when running it. 我开始写一个快速测试但是在运行时我遇到了困难。

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');
  });
});

As a result I get a fail with this log : 结果我得到了这个日志失败:

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)

Could you please help me to figure out what did I do wrong ? 你能帮我弄清楚我做错了什么吗?

Thank you very much for your precious help :-) 非常感谢您的宝贵帮助:-)

You need to instantiate the controller. 您需要实例化控制器。

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

with

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

Also, 也,

can you modify your code 你可以修改你的代码吗?

 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();
  });

Remove the httpBackend from the beforeEach and check 从beforeEach中删除httpBackend并检查

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM