如何在Angular中对组件进行单元测试?

时间:2016-03-09 07:39:12

标签: javascript angularjs unit-testing

我正在测试我在网上找到的外部凉亭组件。它在我的代码上按预期工作,但我无法对其进行单元测试。

我的代码:

控制器:

function testCtrl(externalComponent) {
   //other codes
   externalComponent.loadFile('test.txt').then(function(res) {
       console.log(res)
   })

单元测试

describe..
    beforeEach(module('testApp'));
    beforeEach(inject(function($injector) {
        externalComponent = $injector.get('externalComponent');
        $rootScope = $injector.get('$rootScope');
        $httpBackend = $injector.get('$httpBackend');    
    });

    describe('my test', function () {
        beforeEach(function () {

        });

        it('should test external component', function () {
            //not sure how to test external component. 
            $httpBackend.flush()
        });
    })
}

1 个答案:

答案 0 :(得分:1)

下面的代码是根据代码测试单元测试的一般方法

控制器代码:

function testCtrl(externalComponent,$scope) {
   //other codes
   externalComponent.loadFile('test.txt').then(function(res) {
       $scope.data = res;
   })
}

测试代码:

beforeEach(module('testApp'));
beforeEach(inject(function($injector) {
    $controller = $injector.get('$controller')
    externalComponent = $injector.get('externalComponent');
    $rootScope = $injector.get('$rootScope');
    $httpBackend = $injector.get('$httpBackend');    
});

describe('my test', function () {
    var testCtrl, data = {a:1}, $scope = {};
    beforeEach(function () {
       $httpBackend.when('GET', '/test.txt')
                        .respond(data)
       testCtrl = $controller('testCtrl', { $scope: $scope });
    });

    it('should test external component', function () {
        //not sure how to test external component. 
        $httpBackend.flush()
        expect($scope.data).toEqual(data);
    });
  })
}

解释

  • httpbackend处理get test.txt请求
  • 控制器已创建
  • 期望数据分配给$ scope.data