在单元测试期间不加载AngularJS指令

时间:2015-03-21 13:08:58

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

这是我对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?当我在浏览器中手动执行相同操作时。

1 个答案:

答案 0 :(得分:0)

问题在于这行单元测试:

beforeEach(angular.module('myContainerModule'))

必须是:

beforeEach(module('myContainerModule'))