[Unit Testing] Angular Test component with required

时间:2024-06-26 15:36:32
export default (ngModule) => {
describe('Table Item component', () => { let $compile, directiveElem, directiveCtrl, $scope, state, parentElement; beforeEach(window.module(ngModule.name));
beforeEach(inject(function (_$compile_, _$rootScope_, _$state_) {
$compile = _$compile_;
$scope = _$rootScope_.$new(); state = _$state_;
spyOn(state, 'go');
spyOn(state, 'transitionTo'); directiveElem = getCompiledElement();
directiveCtrl = directiveElem.controller('ttmdTableItem');
})); it('should have the controller defined', () => {
expect(directiveCtrl).toBeDefined();
}); it('should have the parent controller defined', () => {
expect(directiveCtrl.listCtrl).toBeDefined();
}); it('should include desktop item', () => {
expect(directiveElem.find('ttmd-desktop-item').length).toEqual();
}); it('should include mobile item', () => {
console.log(parentElement);
directiveElem = getCompiledElement(true);
directiveCtrl = directiveElem.controller('ttmdTableItem');
$scope.$digest();
expect(directiveElem.find('ttmd-mobile-item').length).toEqual();
}); function getCompiledElement(b) { $scope.item = {
"serviceCode": "1-655-834-8324",
"username": "Johann Homenick",
"amount": "4.37",
"dueDate": "2016-06-07T07:15:02.720Z"
}; $scope.headers = [
'id',
'number',
'username',
'amount',
'due date'
];
const
mockParentController = {
goMobile() {
return b || false;
}
};
parentElement = angular.element('<div><ttmd-table-item item="item" headers="headers"><ttmd-actions></ttmd-table-item></div>');
parentElement.data('$ttmdTableController', mockParentController); const compiledDirective = $compile(parentElement)($scope)
.find('ttmd-table-item');
$scope.$digest();
return compiledDirective;
}
});
};

------------------------

Child:

class TtmdTableItemController {
constructor(ttMdTable) {
this.ttMdTable = ttMdTable;
} getSelectedItem(){
return this.item;
}
} const ttmdTableItemComponent = {
bindings: {
item: '=',
headers: '<',
hasTransclude: '<'
},
transclude: true,
replace: true,
require: {
'listCtrl': '^ttmdTable'
},
controller: TtmdTableItemController,
controllerAs: 'vm',
template: require('./table-item.html')
}; export default (ngModule) => {
ngModule.component('ttmdTableItem', ttmdTableItemComponent);
}

parent:

class TtmdTableController {
constructor(PaginationModel, $transclude) { ....
} goMobile() {
return this.model.goMobile();
} } const ttmdTableComponent = {
bindings: {
...
},
transclude: {
'actions': '?ttmdActions'
},
controller: TtmdTableController,
controllerAs: 'vm',
template: require('./ttmd-table.html')
}; export default (ngModule) => {
ngModule.component('ttmdTable', ttmdTableComponent);
}