【问题标题】:AngularJS directive isn't loaded during unit test在单元测试期间未加载 AngularJS 指令
【发布时间】:2015-03-21 13:08:57
【问题描述】:

这是我对 Karma 的配置:

options: {
    browsers: ['PhantomJS'],
    frameworks: ['jasmine'],
    plugins: [
        'karma-jasmine', 
        'karma-phantomjs-launcher' 
    ],
    reporters: 'dots',
    urlRoot: '/',
    autoWatch: false,
    background: false,
    singleRun: true,
    basePath: '.',
},
tests: {
    files: {
        src: [
            'lib/angular/build/angular.js',
            'lib/angular/build/angular-mocks.js',
            'src/components/**/*.js'
        ]
    }
}

我有以下指令:

angular.module('myContainerModule', []).directive('myContainer', function() {
    return {
        restrict: 'E',
        scope: {
        },
        replace: true,
        transclude: true,
        template: '<section ng-transclude></section>',
        compile: function() {
            console.log('compile');

            return {
                pre: function() {
                    console.log('pre-link');
                },
                post: function() {
                    console.log('post-link');
                }
            };
        },
        controller: function() {
            console.log('controller')
        }
    };
})

还有单元测试:

describe('myContainer', function () {

    var element, scope;

    beforeEach(angular.module('myContainerModule'))
    beforeEach(inject(function($rootScope, $compile) {
        element = angular.element(
            '<my-container>' +
            '   {{foo}}' +
            '</my-container>'
        );

        scope = $rootScope;
        scope.foo = 'bar';

        $compile(element)(scope);
        scope.$digest();
    }))

    it('should be replaced by a `section` tag', function() {
        console.log(element[0].outerHTML);
        expect(element[0].tagName).toBe('SECTION');
    })
})

测试运行者告诉我:

Running "karma:tests" (karma) task
INFO [karma]: Karma v0.12.31 server started at http://localhost:9876/
INFO [launcher]: Starting browser PhantomJS
INFO [PhantomJS 1.9.8 (Linux)]: Connected on socket 1XZDEfFUCHhoCoH7a5LR with id 14712662
LOG: '<my-container class="ng-binding ng-scope">    bar</my-container>'
..
PhantomJS 1.9.8 (Linux) Container should be replaced by a `section` tag FAILED
    Expected 'MY-CONTAINER' to be 'SECTION'.
        at [...]

为什么指令myContainer 被忽略?当我在浏览器中手动执行相同操作时,它可以工作。

【问题讨论】:

    标签: angularjs unit-testing angularjs-directive karma-runner karma-jasmine


    【解决方案1】:

    问题出在单元测试这一行:

    beforeEach(angular.module('myContainerModule'))
    

    必须是:

    beforeEach(module('myContainerModule'))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-06
      • 1970-01-01
      • 1970-01-01
      • 2014-05-23
      • 2015-09-15
      • 1970-01-01
      • 1970-01-01
      • 2017-04-30
      相关资源
      最近更新 更多