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

标签 javascript angularjs unit-testing

我正在测试我在网上找到的外部 Bower 组件。它在我的代码上按预期工作,但我在对其进行单元测试时遇到了麻烦。

我的代码:

Controller :

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

最佳答案

下面的代码是基于代码测试单元测试的通用方法

Controller 代码:

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 请求
  • Controller 已创建
  • 期望数据分配给 $scope.data

关于javascript - 如何在 Angular 中对组件进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35885658/

相关文章:

javascript - 如何在ejs标签中插入javascript变量

javascript - JavaScript 中有 Set 字面量吗?

javascript - #<Task :0x007f91f6442390> 的未定义方法 `upcase'

javascript - 从 iframe 关闭 Angular md-dialog

c# - "Method ...ClassInitialize has wrong signature ..."是什么意思?

javascript - 在 Safari 上获取响应式图片的 currentSrc

javascript - 如何在 next.js getInitialProps 中调用 Prismic API?

javascript - 不能使用 Angular 本地存储

c# - 为什么我在模拟测试对象上得到空引用异常?

c# - 如何在 .NET 中测试可执行文件