使用jasmine/carma在PhantomJS中导入角度组件



下面的单元测试在Chrome中有效(因为它对HTML导入的原生支持),但我很难让它与PhantomJS(以及其他浏览器)一起工作。

我正在尝试polyfill导入('webcomponents.js/HTMLImports.min.js'),但它没有任何效果。

karma.conf.js

module.exports = function(config) {
config.set({
frameworks: ['jasmine'],
plugins: [
'karma-phantomjs-launcher',
'karma-chrome-launcher',
'karma-jasmine'
],
files: [
'node_modules/angular/angular.js',
'node_modules/angular-mocks/angular-mocks.js',
'node_modules/webcomponents.js/HTMLImports.min.js',
'component/so-example.html',
'test/test.spec.js'
],
port: 9876,
browsers: ['Chrome', 'PhantomJS']
});
};

component/so-sample.html

<script>
(function () {
var soExampleComponent = {
transclude: true,
bindings: {
number: '@'
},
template: '<span class="compiled">{{$ctrl.number}}</span>'
};
angular.module('so.components.example', []).component('soExample', soExampleComponent);
})();
</script>

test/test.spec.js

describe('<so-example>', function () {
var $scope, el;
beforeEach(module('so.components.example'));
beforeEach(inject(function ($compile, $rootScope) {
$scope = $rootScope.$new();
el = $compile('<so-example number="{{ 3 }}"></so-example>')($scope)[0];
$scope.$digest();
}));
it('should import and compile', function () {
expect(el.querySelector('.compiled').textContent).toBe('3');
});
});

PhantomJS 的错误

forEach@C:/Temp/so-example/node_modules/angular/angular.js:322:24
loadModules@C:/Temp/so-example/node_modules/angular/angular.js:4591:12
createInjector@C:/Temp/so-example/node_modules/angular/angular.js:4513:30
workFn@C:/Temp/so-example/node_modules/angular-mocks/angular-mocks.js:3060:60
C:/Temp/so-example/node_modules/angular/angular.js:4631:53
TypeError: undefined is not an object (evaluating 'el.querySelector') in C:/Temp/so-example/test/test.spec.js (line 14)
C:/Temp/so-example/test/test.spec.js:14:14

经过大约一天的思考,发现解决方案非常简单。

我们可以强制jasmine等待导入完成,方法是在任何依赖HTML导入的测试之前执行以下块。

// Wait for the HTML Imports polyfill to finish before running anything else
beforeAll(function(done) {
window.addEventListener('HTMLImportsLoaded', done);
});

我已经将其放入一个单独的文件中,在karma.conf.js中引用该文件,然后再引用所有其他spec.js文件。

然而,它可以被放置在单个describe块中,或者如果其他地方不需要它,则可以被放置到单个spec.js中。

最新更新