简体   繁体   中英

How to unit test a component in Angular?

I am testing a external bower component I found online. It was working as expected on my code but I have trouble unit test it.

My codes:

Controller:

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

Unit test

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

the code under is a general approach of testing a unit test base on your code

controller code:

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

test code:

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

explanation :

  • httpbackend handling the get test.txt request
  • controller created
  • expect data to assign to $scope.data

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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