我有一个组件测试,我使用angularjs' $controllerProvider
模拟组件的控制器。注入工作正常但控制器上下文this
即使在注册期间也是undefined
。
我的组件
import templateUrl from './pdf-export-modal.html.pug';
import './pdf-export-modal.less';
export default {
templateUrl,
bindings: {
onClose: '&',
},
controller: 'PdfExportModalCtrl',
};
和组件测试文件
import angular from 'angular';
describe('component: pdf-export-modal', () => {
let $rootScope;
let $compile;
let scope;
let el;
let html;
let ctrl;
beforeEach(angular.mock.module('mainModule', ($controllerProvider) => {
$controllerProvider.register('PdfExportModalCtrl', () => {
ctrl = this;
console.log(ctrl, this); // both are undefined here
});
}));
beforeEach(inject((_$rootScope_, _$compile_) => {
$rootScope = _$rootScope_;
$compile = _$compile_;
scope = $rootScope.$new();
html = "<pdf-export-modal on-close='onClose'/>";
scope.onClose = jasmine.createSpy('onClose');
el = $compile(html)(scope);
scope.$apply();
}));
describe('selecting compact', () => {
// test
});
});
答案 0 :(得分:0)
问题出在ES6自动装订上。箭头函数使用this
的测试类instead of creating a new one中的PdfModalCtrl
上下文。删除了箭头功能并使用了ES5语法使其正常工作。
beforeEach(angular.mock.module('mainModule', ($controllerProvider) => {
$controllerProvider.register('PdfExportModalCtrl', function () {
ctrl = this;
console.log(ctrl); //new context is created for the controller
});
}));