How to use serviceCustomize method in ng-mocks

Best JavaScript code snippet using ng-mocks

service.directive.js

Source:service.directive.js Github

copy

Full Screen

1/**2 * Object Service Directive3 *4 * Description5 */6(function () {7 'use strict';8 angular9 .module('southWest.object.service')10 .directive('svcPredefineTable', predefineTable)11 .directive('svcCustomizeTable', customizeTable);12 function predefineTable(ServicePredefine) {13 var obj = {14 scope: false,15 restrict: 'E',16 require: '^dtable',17 replace: true,18 templateUrl: '/templates/object/service/predefineTable.html',19 link: link20 };21 return obj;22 //////////23 function link(scope, element, attr, ctrl) {24 ctrl.setConfig({25 name: 'item',26 pagination: true,27 scrollable: false,28 totalCount: true,29 getAll: getAll,30 getCount: getCount,31 search: search,32 fields: ['name', 'description'],33 advancedSearch: 'predefineServers',34 advancedSearchOptions:[35 {'name': 'name', 'display': '服务名称', 'input': 'string', 'option': false, value: ""},36 {'name': 'description', 'display': '描述', 'input': 'string', 'option': false, value: ""},37 {'name': 'createdBy', 'display': '端口', 'input': 'string', 'option': false, value: ""}38 ]39 });40 function getAll(params) {41 // var a = ctrl.q;42 var payload = params || {};43 scope.skip = params.$skip || 0;//序号显示用44 return ServicePredefine.getAll(payload);45 }46 function getCount(params) {47 var payload = params || {};48 return ServicePredefine.getCount(payload);49 }50 function search(params) {51 return getAll(params);52 }53 ctrl.selectedItems = {};54 ctrl.selectAll = function () {55 ctrl.selectedItems = {};56 ctrl.table.forEach(function (service) {57 ctrl.selectedItems[service.name] = ctrl.selectAllValue;58 });59 };60 }61 }62 function customizeTable($rootScope, $state, $q, $timeout, $modal, $log, Enum, Task, ServiceCustomize) {63 var obj = {64 scope: false,65 restrict: 'E',66 require: '^dtable',67 replace: true,68 templateUrl: '/templates/object/service/customizeTable.html',69 link: link70 };71 return obj;72 //////////73 function link(scope, element, attr, ctrl) {74 ctrl.setConfig({75 name: 'item',76 pagination: true,77 scrollable: false,78 totalCount: true,79 getAll: getAll,80 getCount: getCount,81 search: search,82 //TODO: _policyRefers的搜索,目前MW尚不支持,待支持后再调试83 //fields: ['name', 'description', '_policyRefers'],84 fields: ['name', 'description'],85 advancedSearch: 'customizedServers',86 advancedSearchOptions:[87 {'name': 'name', 'display': '服务名称', 'input': 'string', 'option': false, value: ""},88 //{'name': '_policyRefers', 'display': '策略引用', 'input': 'string', 'option': false, value: ""},89 {'name': 'description', 'display': '描述', 'input': 'string', 'option': false, value: ""},90 {'name': 'createdBy', 'display': '端口', 'input': 'string', 'option': false, value: ""}91 ]92 });93 function getAll(params) {94 var payload = params || {};95 scope.skip = params.$skip || 0;//序号显示用96 return ServiceCustomize.getAll(payload);97 }98 function getCount(params) {99 var payload = params || {};100 return ServiceCustomize.getCount(payload);101 }102 function search(params) {103 return getAll(params);104 }105 ctrl.selectedItems = {};106 ctrl.selectAll = function () {107 ctrl.selectedItems = {};108 ctrl.table.forEach(function (service) {109 ctrl.selectedItems[service.name] = ctrl.selectAllValue;110 });111 };112 ctrl.selectedChanged = function () {113 var selectedAll = true;114 var hasSelected = false;115 var singleSelected = false;116 ctrl.table.forEach(function (service) {117 if (ctrl.selectedItems[service.name] === undefined || ctrl.selectedItems[service.name] === null) {118 singleSelected = false;119 } else {120 singleSelected = ctrl.selectedItems[service.name];121 }122 hasSelected = hasSelected || singleSelected;123 selectedAll = selectedAll && singleSelected;124 });125 ctrl.selectAllValue = selectedAll ? true : (hasSelected ? null : false);126 };127 //获取是否具有编辑权限128 scope.privilegeName = 'OBJECT_SERVICE';129 var values = Enum.get('privilege').filter(function (pri) {130 return pri.name === scope.privilegeName;131 });132 var actionValue = values && values.length > 0 ? values[0].actionValue : 1;133 scope.isNoEditPri = (actionValue < 28);134 ctrl.addNewService = function () {135 var modalInstance = $modal.open({136 templateUrl: 'service-customize-add-new.html',137 size: 'lg',138 controller: ModalInstanceCtrl139 });140 modalInstance.result.then(function () {141 //do nothing.142 }, function () {143 $log.info('Modal dismissed at: ' + new Date());144 });145 function ModalInstanceCtrl($scope, $modalInstance, ServiceCustomize, formatVal) {146 $scope.newService={};147 $scope.newRule={type:'TCP'}; //服务规则对象148 $scope.rules=[]; //服务规则列表149 //自定义validation150 function checkNameUnique(name){151 var services = ctrl.table;152 var rst = true;153 if(name && services){154 services.some(function(service){155 if(service.name === name){156 rst = false;157 return true;158 }159 });160 }161 return rst;162 }163 function checkNameCharacter(name){164 if(name && !formatVal.validateObjectAssetsName(name)){165 return false;166 }167 return true;168 }169 $scope.checkNameVal = function(name){170 var rst = checkNameCharacter(name);171 if(!rst){172 $scope.nameValMsg = '支持中文、字母、数字、"-"、"_"的组合,3-20个字符';173 }else{174 rst = checkNameUnique(name);175 if(!rst){176 $scope.nameValMsg = '已定义该名称的服务,请更换其他服务名称';177 }178 }179 return rst;180 };181 function checkPort(port, isMinAction, relVal){182 if(port && (formatVal.validatePort(port) || Number(port)<1)){183 if(isMinAction && port.toUpperCase() === 'ANY' && relVal !== 'ANY'){184 return true;185 }186 return false;187 }188 return true;189 }190 $scope.checkDestPortVal = function(port, flag){191 $scope.isDestPortsInvalid = false;192 var isMinAction = (flag <= 0);193 var min = $scope.newRule.minDstPort;194 var max = $scope.newRule.maxDstPort;195 var tempMinSrcPort = $scope.newRule.minSrcPort ? $scope.newRule.minSrcPort.toUpperCase() : '';196 var isMinValid = min?checkPort(min, true, tempMinSrcPort):true;197 var isMaxValid = max?checkPort(max, false):true;198 var rst = isMinValid && isMaxValid;199 if(!rst){200 $scope.destPortValMsg = '请输入有效' + (!isMinValid?'最小':(!isMaxValid?'最大':'')) + '端口号';201 if((isMinAction && isMinValid) || (!isMinAction && isMaxValid)){202 rst = true;203 }204 }else{205 if(min && max && Number(min)>Number(max)){206 $scope.isDestPortsInvalid = true;207 $scope.destPortValMsg = '端口输入不合法,最大端口不能小于最小端口';208 }209 }210 return rst;211 };212 $scope.checkSourcePortVal = function(port, flag){213 $scope.isSourcePortsInvalid = false;214 var isMinAction = (flag <= 0);215 var min = $scope.newRule.minSrcPort;216 var max = $scope.newRule.maxSrcPort;217 var tempMinDstPort = $scope.newRule.minDstPort ? $scope.newRule.minDstPort.toUpperCase() : '';218 var isMinValid = min?checkPort(min, true, tempMinDstPort):true;219 var isMaxValid = max?checkPort(max, false):true;220 var rst = isMinValid && isMaxValid;221 if(!rst){222 $scope.sourcePortValMsg = '请输入有效' + (!isMinValid?'最小':(!isMaxValid?'最大':'')) + '端口号';223 if((isMinAction && isMinValid) || (!isMinAction && isMaxValid)){224 rst = true;225 }226 }else{227 if(min && max && Number(min)>Number(max)){228 $scope.isSourcePortsInvalid = true;229 $scope.sourcePortValMsg = '端口输入不合法,最大端口不能小于最小端口';230 }231 }232 return rst;233 };234 $scope.$watch("[newRule.minSrcPort, newRule.minDstPort]", function(newVal){235 //源端口最小为any,隐藏最大端口236 if(newVal[0] && newVal[0].toUpperCase() === 'ANY'){237 $scope.newRule.maxSrcPort='';238 $scope.srcMaxPortHide = true;239 }else{240 $scope.srcMaxPortHide = false;241 }242 //目标端口最小为any,隐藏最大端口243 if(newVal[1] && newVal[1].toUpperCase() === 'ANY'){244 $scope.newRule.maxDstPort='';245 $scope.destMaxPortHide = true;246 }else{247 $scope.destMaxPortHide = false;248 }249 });250 $scope.$watch("[newRule.minSrcPort, newRule.minDstPort, newRule.maxSrcPort, newRule.maxDstPort]", function(newVal){251 //源端口最大/小不填,最小/大被赋值为与最小/大相同的值252 if(newVal[0] && newVal[0].toUpperCase() !== 'ANY' && !newVal[2]){253 $scope.newRule.maxSrcPort=newVal[0];254 }255 if(newVal[2] && newVal[2].toUpperCase() !== 'ANY' && !newVal[0]){256 $scope.newRule.minSrcPort=newVal[2];257 }258 //目标端口最大/小不填,最小/大被赋值为与最小/大相同的值259 if(newVal[1] && newVal[1].toUpperCase() !== 'ANY' && !newVal[3]){260 $scope.newRule.maxDstPort=newVal[1];261 }262 if(newVal[3] && newVal[3].toUpperCase() !== 'ANY' && !newVal[1]){263 $scope.newRule.minDstPort=newVal[3];264 }265 });266 $scope.addNewRule = function (formValid) {267 if(formValid){268 var newRule = angular.copy($scope.newRule);269 $scope.rules.push(newRule);270 }271 };272 $scope.deleteRule = function (index) {273 $scope.rules.splice(index,1);274 };275 $scope.ok = function (formValid) {276 if(formValid){277 $scope.newService.serverRules = $scope.rules;278 $scope.isAddingService = true;279 ServiceCustomize.addNewService([$scope.newService], function(taskInfo, err) {280 var cancellable = $scope.$on('closeAddModal', function(){281 $scope.isAddingService = false;282 $modalInstance.close();283 cancellable();284 });285 if (err) {286 $scope.$emit('closeAddModal');287 $rootScope.addAlert({288 type: 'danger',289 content: (err.data ? ('自定义服务添加失败:' + err.data) : '自定义服务添加失败')290 });291 } else {292 var taskId = taskInfo.taskId;293 (function countdown(counter) {294 var checkAdding = $timeout(function () {295 Task.getTask(taskId).then(function (data) {296 if (data.data.state === 'SUCCESS') {297 $scope.$emit('closeAddModal');298 $state.reload().then(function () {299 $rootScope.addAlert({300 type: 'success',301 content: '自定义服务添加成功'302 });303 });304 $timeout.cancel(checkAdding);305 } else if (data.data.state === 'FAILED' || data.data.state === 'REJECTED') {306 $scope.$emit('closeAddModal');307 $rootScope.addAlert({308 type: 'danger',309 content: (data.data.reason ? ('自定义服务添加失败:' + data.data.reason) : '自定义服务添加失败')310 });311 $timeout.cancel(checkAdding);312 } else if (data.data.state === 'PENDING' || 'PROCESSING' || 'PAUSE') {313 if (counter > 0) {314 countdown(counter - 1);315 } else {316 $scope.$emit('closeAddModal');317 $rootScope.addAlert({318 type: 'danger',319 content: '自定义服务添加超时'320 });321 $timeout.cancel(checkAdding);322 }323 } else {324 $scope.$emit('closeAddModal');325 $rootScope.addAlert({326 type: 'danger',327 content: (data.data.reason ? ('自定义服务添加失败:' + data.data.reason) : '自定义服务添加失败')328 });329 $timeout.cancel(checkAdding);330 }331 });332 }, 1000);333 })(30);334 }335 });336 }337 };338 $scope.cancel = function () {339 $modalInstance.dismiss('cancel');340 };341 }342 };343 ctrl.editService = function (svcObject) {344 var modalInstance = $modal.open({345 templateUrl: 'service-customize-edit.html',346 size: 'lg',347 controller: ModalInstanceCtrl348 });349 modalInstance.result.then(function () {350 //do nothing.351 }, function () {352 $log.info('Modal dismissed at: ' + new Date());353 });354 function ModalInstanceCtrl($scope, $modalInstance, ServiceCustomize, formatVal) {355 $scope.isEditDisabled = true;356 $scope.editService = angular.copy(svcObject);357 $scope.newRule={type:'TCP'}; //服务规则对象358 $scope.rules = []; //服务规则列表359 if(angular.isArray($scope.editService.serverRules)){360 $scope.rules = $scope.editService.serverRules;361 }362 //自定义validation363 function checkNameUnique(name){364 var services = ctrl.table;365 var rst = true;366 if(name && services){367 services.some(function(service){368 if(service.name === name && service.name !== svcObject.name){369 rst = false;370 return true;371 }372 });373 }374 return rst;375 }376 function checkNameCharacter(name){377 if(name && !formatVal.validateObjectAssetsName(name)){378 return false;379 }380 return true;381 }382 $scope.checkNameVal = function(name){383 var rst = checkNameCharacter(name);384 if(!rst){385 $scope.nameValMsg = '支持中文、字母、数字、"-"、"_"的组合,3-20个字符';386 }else{387 rst = checkNameUnique(name);388 if(!rst){389 $scope.nameValMsg = '已定义该名称的服务,请更换其他服务名称';390 }391 }392 return rst;393 };394 function checkPort(port, isMinAction, relVal){395 if(port && (formatVal.validatePort(port) || Number(port)<1)){396 if(isMinAction && port.toUpperCase() === 'ANY' && relVal !== 'ANY'){397 return true;398 }399 return false;400 }401 return true;402 }403 $scope.checkDestPortVal = function(port, flag){404 $scope.isDestPortsInvalid = false;405 var isMinAction = (flag <= 0);406 var min = $scope.newRule.minDstPort;407 var max = $scope.newRule.maxDstPort;408 var tempMinSrcPort = $scope.newRule.minSrcPort ? $scope.newRule.minSrcPort.toUpperCase() : '';409 var isMinValid = min?checkPort(min, true, tempMinSrcPort):true;410 var isMaxValid = max?checkPort(max, false):true;411 var rst = isMinValid && isMaxValid;412 if(!rst){413 $scope.destPortValMsg = '请输入有效' + (!isMinValid?'最小':(!isMaxValid?'最大':'')) + '端口号';414 if((isMinAction && isMinValid) || (!isMinAction && isMaxValid)){415 rst = true;416 }417 }else{418 if(min && max && Number(min)>Number(max)){419 $scope.isDestPortsInvalid = true;420 $scope.destPortValMsg = '端口输入不合法,最大端口不能小于最小端口';421 }422 }423 return rst;424 };425 $scope.checkSourcePortVal = function(port, flag){426 $scope.isSourcePortsInvalid = false;427 var isMinAction = (flag <= 0);428 var min = $scope.newRule.minSrcPort;429 var max = $scope.newRule.maxSrcPort;430 var tempMinDstPort = $scope.newRule.minDstPort ? $scope.newRule.minDstPort.toUpperCase() : '';431 var isMinValid = min?checkPort(min, true, tempMinDstPort):true;432 var isMaxValid = max?checkPort(max, false):true;433 var rst = isMinValid && isMaxValid;434 if(!rst){435 $scope.sourcePortValMsg = '请输入有效' + (!isMinValid?'最小':(!isMaxValid?'最大':'')) + '端口号';436 if((isMinAction && isMinValid) || (!isMinAction && isMaxValid)){437 rst = true;438 }439 }else{440 if(min && max && Number(min)>Number(max)){441 $scope.isSourcePortsInvalid = true;442 $scope.sourcePortValMsg = '端口输入不合法,最大端口不能小于最小端口';443 }444 }445 return rst;446 };447 $scope.$watch("[newRule.minSrcPort, newRule.minDstPort]", function(newVal){448 //源端口最小为any,隐藏最大端口449 if(newVal[0] && newVal[0].toUpperCase() === 'ANY'){450 $scope.newRule.maxSrcPort='';451 $scope.srcMaxPortHide = true;452 }else{453 $scope.srcMaxPortHide = false;454 }455 //目标端口最小为any,隐藏最大端口456 if(newVal[1] && newVal[1].toUpperCase() === 'ANY'){457 $scope.newRule.maxDstPort='';458 $scope.destMaxPortHide = true;459 }else{460 $scope.destMaxPortHide = false;461 }462 });463 $scope.$watch("[newRule.minSrcPort, newRule.minDstPort, newRule.maxSrcPort, newRule.maxDstPort]", function(newVal){464 //源端口最大/小不填,最小/大被赋值为与最小/大相同的值465 if(newVal[0] && newVal[0].toUpperCase() !== 'ANY' && !newVal[2]){466 $scope.newRule.maxSrcPort=newVal[0];467 }468 if(newVal[2] && newVal[2].toUpperCase() !== 'ANY' && !newVal[0]){469 $scope.newRule.minSrcPort=newVal[2];470 }471 //目标端口最大/小不填,最小/大被赋值为与最小/大相同的值472 if(newVal[1] && newVal[1].toUpperCase() !== 'ANY' && !newVal[3]){473 $scope.newRule.maxDstPort=newVal[1];474 }475 if(newVal[3] && newVal[3].toUpperCase() !== 'ANY' && !newVal[1]){476 $scope.newRule.minDstPort=newVal[3];477 }478 });479 $scope.addNewRule = function (formValid) {480 if(formValid){481 var newRule = angular.copy($scope.newRule);482 $scope.rules.push(newRule);483 }484 };485 $scope.deleteRule = function (index) {486 $scope.rules.splice(index,1);487 };488 $scope.ok = function (formValid) {489 if(formValid){490 $scope.isEdittingService = true;491 ServiceCustomize.updateService([$scope.editService], function(taskInfo, err) {492 var cancellable = $scope.$on('closeAddModal', function(){493 $scope.isEdittingService = false;494 $modalInstance.close();495 cancellable();496 });497 if (err) {498 $scope.$emit('closeAddModal');499 $rootScope.addAlert({500 type: 'danger',501 content: (err.data ? ('自定义服务修改失败:' + err.data) : '自定义服务修改失败')502 });503 } else {504 var taskId = taskInfo.taskId;505 (function countdown(counter) {506 var checkEditting = $timeout(function () {507 Task.getTask(taskId).then(function (data) {508 if (data.data.state === 'SUCCESS') {509 $scope.$emit('closeAddModal');510 $state.reload().then(function () {511 $rootScope.addAlert({512 type: 'success',513 content: '自定义服务修改成功'514 });515 });516 $timeout.cancel(checkEditting);517 } else if (data.data.state === 'FAILED' || data.data.state === 'REJECTED') {518 $scope.$emit('closeAddModal');519 $rootScope.addAlert({520 type: 'danger',521 content: (data.data.reason ? ('自定义服务修改失败:' + data.data.reason) : '自定义服务修改失败')522 });523 $timeout.cancel(checkEditting);524 } else if (data.data.state === 'PENDING' || 'PROCESSING' || 'PAUSE') {525 if (counter > 0) {526 countdown(counter - 1);527 } else {528 $scope.$emit('closeAddModal');529 $rootScope.addAlert({530 type: 'danger',531 content: '自定义服务修改超时'532 });533 $timeout.cancel(checkEditting);534 }535 } else {536 $scope.$emit('closeAddModal');537 $rootScope.addAlert({538 type: 'danger',539 content: (data.data.reason ? ('自定义服务修改失败:' + data.data.reason) : '自定义服务修改失败')540 });541 $timeout.cancel(checkEditting);542 }543 });544 }, 1000);545 })(30);546 }547 });548 }549 };550 $scope.cancel = function () {551 $modalInstance.dismiss('cancel');552 };553 }554 };555 ctrl.viewService = function (svcObject) {556 var modalInstance = $modal.open({557 templateUrl: 'service-customize-edit.html',558 size: 'lg',559 controller: ModalInstanceCtrl560 });561 modalInstance.result.then(function () {562 //do nothing.563 }, function () {564 $log.info('Modal dismissed at: ' + new Date());565 });566 function ModalInstanceCtrl($scope, $modalInstance) {567 $scope.isViewOnly = true;568 $scope.editService = svcObject;569 $scope.newRule={type:'TCP'}; //服务规则对象570 $scope.rules = $scope.editService.serverRules; //服务规则列表571 $scope.checkNameVal = function(){572 return true;573 };574 $scope.checkDestPortVal = function(){575 return true;576 };577 $scope.checkSourcePortVal = function(){578 return true;579 };580 $scope.ok = function () {581 $modalInstance.close();582 };583 $scope.cancel = function () {584 $modalInstance.dismiss('cancel');585 };586 }587 };588 ctrl.deleteService = function() {589 var selectedItems = ctrl.selectedItems;590 var itemIds = [];591 if (selectedItems) {592 for (var name in selectedItems) {593 if (selectedItems[name]) {594 itemIds.push(name);595 }596 }597 }598 if (itemIds.length !== 0) {599 var deferred = $q.defer();600 $rootScope.serviceDeleteTaskPromise = deferred.promise;601 ServiceCustomize.deleteService(itemIds, function (taskInfo, err) {602 if (err) {603 $rootScope.addAlert({604 type: 'danger',605 content: (err.data ? ('自定义服务删除失败:' + err.data) : '自定义服务删除失败')606 });607 deferred.resolve('fail');608 } else {609 var taskId = taskInfo.taskId;610 (function countdown(counter) {611 var checkServiceDeletion = $timeout(function () {612 Task.getTask(taskId).then(function (data) {613 if (data.data.state === 'SUCCESS') {614 $state.reload().then(function () {615 $rootScope.addAlert({616 type: 'success',617 content: '自定义服务删除成功'618 });619 });620 deferred.resolve('success');621 $timeout.cancel(checkServiceDeletion);622 } else if (data.data.state === 'FAILED' || data.data.state === 'REJECTED') {623 $rootScope.addAlert({624 type: 'danger',625 content: (data.data.reason ? ('自定义服务删除失败:' + data.data.reason) : '自定义服务删除失败')626 });627 deferred.resolve('fail');628 $timeout.cancel(checkServiceDeletion);629 } else if (data.data.state === 'PENDING' || 'PROCESSING' || 'PAUSE') {630 if (counter > 0) {631 countdown(counter - 1);632 } else {633 $rootScope.addAlert({634 type: 'danger',635 content: '自定义服务删除超时'636 });637 deferred.resolve('timeout');638 $timeout.cancel(checkServiceDeletion);639 }640 } else {641 $rootScope.addAlert({642 type: 'danger',643 content: (data.data.reason ? ('自定义服务删除失败:' + data.data.reason) : '自定义服务删除失败')644 });645 deferred.resolve('fail');646 $timeout.cancel(checkServiceDeletion);647 }648 });649 }, 1000);650 })(30);651 }652 });653 } else {654 $rootScope.addAlert({655 type: 'info',656 content: '请至少选中一条自定义服务'657 });658 }659 };660 }661 }...

Full Screen

Full Screen

test.ng-mocks.spec.ts

Source:test.ng-mocks.spec.ts Github

copy

Full Screen

1import { HttpClientModule } from '@angular/common/http';2import { HttpClientTestingModule } from '@angular/common/http/testing';3import { inject, TestBed } from '@angular/core/testing';4import { isMockedNgDefOf, MockBuilder, NG_MOCKS } from 'ng-mocks';5import {6 KeepComponent,7 MockComponent,8 My1Component,9 My2Component,10 My3Component,11 MyComponent,12} from './spec.components.fixtures';13import {14 KeepDirective,15 MockDirective,16} from './spec.directives.fixtures';17import {18 ModuleKeep,19 ModuleMock,20 MyModule,21} from './spec.modules.fixtures';22import {23 KeepPipe,24 MockPipe,25 RestorePipe,26} from './spec.pipes.fixtures';27import {28 ServiceCustomize,29 ServiceKeep,30 ServiceMock,31} from './spec.services.fixtures';32import {33 TOKEN_CUSTOMIZE,34 TOKEN_KEEP,35 TOKEN_MOCK,36} from './spec.tokens.fixtures';37describe('MockBuilder:ngMocks', () => {38 beforeEach(async () => {39 const ngModule = MockBuilder(MyComponent, MyModule)40 .keep(ModuleKeep)41 .keep(KeepComponent)42 .keep(KeepDirective)43 .keep(KeepPipe)44 .keep(ServiceKeep)45 .keep(TOKEN_KEEP)46 .replace(HttpClientModule, HttpClientTestingModule)47 .mock(ModuleMock)48 .mock(MockComponent)49 .mock(MockDirective)50 .mock(MockPipe)51 .mock(ServiceMock) // makes all methods an empty function52 .mock(TOKEN_MOCK) // makes its value undefined53 .mock(ServiceCustomize, {54 getName: () => 'My Customized String',55 })56 .mock(TOKEN_CUSTOMIZE, 'My_Token')57 // Now the pipe will not be replaced with its mock copy.58 .keep(RestorePipe)59 // Even it belongs to the module we want to keep,60 // it will be still replaced with a mock copy.61 .mock(My3Component)62 // and now we want to build our NgModule.63 .build();64 TestBed.configureTestingModule(ngModule);65 // Extra configuration66 TestBed.overrideTemplate(67 My1Component,68 'If we need to tune testBed',69 );70 TestBed.overrideTemplate(My2Component, 'More callbacks');71 return TestBed.compileComponents();72 });73 it('should contain mocks', inject(74 [NG_MOCKS],75 (mocks: Map<any, any>) => {76 // main part77 const myComponent = mocks.get(MyComponent);78 expect(myComponent).toBe(MyComponent);79 const myModule = mocks.get(MyModule);80 expect(isMockedNgDefOf(myModule, MyModule, 'm')).toBeTruthy();81 // keep82 const keepComponent = mocks.get(KeepComponent);83 expect(keepComponent).toBe(keepComponent);84 const keepDirective = mocks.get(KeepDirective);85 expect(keepDirective).toBe(keepDirective);86 const keepPipe = mocks.get(KeepPipe);87 expect(keepPipe).toBe(keepPipe);88 const serviceKeep = mocks.get(ServiceKeep);89 expect(serviceKeep).toBe(ServiceKeep);90 const tokenKeep = mocks.get(TOKEN_KEEP);91 expect(tokenKeep).toBe(TOKEN_KEEP);92 // replace93 const httpClientModule = mocks.get(HttpClientModule);94 expect(httpClientModule).toBe(HttpClientTestingModule);95 // mimic96 const moduleMock = mocks.get(ModuleMock);97 expect(98 isMockedNgDefOf(moduleMock, ModuleMock, 'm'),99 ).toBeTruthy();100 const mockComponent = mocks.get(MockComponent);101 expect(102 isMockedNgDefOf(mockComponent, MockComponent, 'c'),103 ).toBeTruthy();104 const mockDirective = mocks.get(MockDirective);105 expect(106 isMockedNgDefOf(mockDirective, MockDirective, 'd'),107 ).toBeTruthy();108 const mockPipe = mocks.get(MockPipe);109 expect(isMockedNgDefOf(mockPipe, MockPipe, 'p')).toBeTruthy();110 const serviceMock = mocks.get(ServiceMock);111 expect(serviceMock).toBeDefined();112 expect(serviceMock.useFactory).toBeDefined();113 const serviceMockInstance = serviceMock.useFactory();114 expect(serviceMockInstance.getName).toBeDefined();115 expect(serviceMockInstance.getName()).toBeUndefined();116 expect(mocks.has(TOKEN_MOCK)).toBeDefined();117 expect(mocks.get(TOKEN_MOCK)).toBeDefined();118 // customize119 const serviceCustomize = mocks.get(ServiceCustomize);120 expect(serviceCustomize).toBeDefined();121 expect(serviceCustomize.useFactory).toBeDefined();122 const serviceCustomizeInstance = serviceCustomize.useFactory();123 expect(serviceCustomizeInstance.getName).toBeDefined();124 expect(serviceCustomizeInstance.getName()).toEqual(125 'My Customized String',126 );127 const tokenCustomize = mocks.get(TOKEN_CUSTOMIZE);128 expect(tokenCustomize).toBeDefined();129 expect(tokenCustomize.useFactory).toBeDefined();130 const tokenCustomizeValue = tokenCustomize.useFactory();131 expect(tokenCustomizeValue).toEqual('My_Token');132 // restore133 const restorePipe = mocks.get(RestorePipe);134 expect(restorePipe).toBe(restorePipe);135 // mock nested136 const myComponent3 = mocks.get(My3Component);137 expect(138 isMockedNgDefOf(myComponent3, My3Component, 'c'),139 ).toBeTruthy();140 },141 ));...

Full Screen

Full Screen

spec.components.fixtures.ts

Source:spec.components.fixtures.ts Github

copy

Full Screen

1import { Component, ContentChild, Inject, Input, Optional, TemplateRef } from '@angular/core';2import {3 AnythingKeep1,4 AnythingKeep2,5 MyCustomProvider1,6 MyCustomProvider2,7 MyCustomProvider3,8 MyService1,9 MyService2,10 ServiceCustomize,11 ServiceKeep,12 ServiceMock,13} from './spec.services.fixtures';14import { TOKEN_CUSTOMIZE, TOKEN_KEEP, TOKEN_MOCK } from './spec.tokens.fixtures';15@Component({16 selector: 'c-structural',17 template: `18 <div *ngIf="items && items.length">19 <ng-template ngFor [ngForOf]="items" [ngForTemplate]="injectedBlock"></ng-template>20 </div>21 `,22})23export class ContentChildComponent<T> {24 @ContentChild('block', {} as any) public readonly injectedBlock: TemplateRef<any> | undefined;25 @Input() public items: T[] | undefined;26}27@Component({28 selector: 'c-my',29 template: `30 <div>My Content</div>31 <div>MyComponent1: <c-1></c-1></div>32 <div>MyComponent2: <c-2></c-2></div>33 <div>MyComponent3: <c-3></c-3></div>34 <div>KeepComponent: <c-keep></c-keep></div>35 <div>MockComponent: <c-mock></c-mock></div>36 <div>MyDirective: <d-my></d-my></div>37 <div>KeepDirective: <d-keep></d-keep></div>38 <div>39 MockDirective 1: <span *d-mock="let z = a">render {{ z.b }}</span>40 </div>41 <div>42 MockDirective 2: <ng-template d-mock let-z>render {{ z.a }}</ng-template>43 </div>44 <div>MyPipe: {{ 'text' | my }}</div>45 <div>KeepPipe: {{ 'text' | keep }}</div>46 <div>MockPipe: {{ 'text' | mock }}</div>47 <div>CustomizePipe: {{ 'text' | customize }}</div>48 <div>RestorePipe: {{ 'text' | restore }}</div>49 <div>TOKEN_KEEP: {{ t1 }}</div>50 <div>TOKEN_MOCK: {{ t2 }}</div>51 <div>TOKEN_CUSTOMIZE: {{ t3 }}</div>52 <div>AnythingKeep1: {{ anythingKeep1?.getName() }}</div>53 <div>AnythingKeep2: {{ anythingKeep2?.getName() }}</div>54 <div>myCustomProvider1: {{ myCustomProvider1?.getName() }}</div>55 <div>myCustomProvider2: {{ myCustomProvider2?.getName() }}</div>56 <div>myCustomProvider3: {{ myCustomProvider3?.getName() }}</div>57 <div>myService1: {{ myService1?.getName() }}</div>58 <div>myService2: {{ myService2?.getName() }}</div>59 <div>serviceKeep: {{ serviceKeep?.getName() }}</div>60 <div>serviceCustomize: {{ serviceCustomize?.getName() }}</div>61 <div>serviceMock: {{ serviceMock?.getName() }}</div>62 <c-structural>63 <ng-template let-value let-b="a" #block>64 <div>ComponentStructural: {{ value }} {{ b.z }}</div>65 </ng-template>66 </c-structural>67 `,68})69export class MyComponent {70 public constructor(71 @Optional() @Inject(TOKEN_KEEP) public readonly t1: string,72 @Optional() @Inject(TOKEN_MOCK) public readonly t2: string,73 @Optional() @Inject(TOKEN_CUSTOMIZE) public readonly t3: string,74 @Optional() public readonly anythingKeep1: AnythingKeep1,75 @Optional() public readonly anythingKeep2: AnythingKeep2,76 @Optional() public readonly myCustomProvider1: MyCustomProvider1,77 @Optional() public readonly myCustomProvider2: MyCustomProvider2,78 @Optional() public readonly myCustomProvider3: MyCustomProvider3,79 @Optional() public readonly myService1: MyService1,80 @Optional() public readonly myService2: MyService2,81 @Optional() public readonly serviceKeep: ServiceKeep,82 @Optional() public readonly serviceMock: ServiceMock,83 @Optional() public readonly serviceCustomize: ServiceCustomize,84 ) {}85}86@Component({87 selector: 'c-1',88 template: 'MyComponent1',89})90export class My1Component {}91@Component({92 selector: 'c-2',93 template: 'MyComponent2',94})95export class My2Component {}96@Component({97 selector: 'c-3',98 template: 'MyComponent3',99})100export class My3Component {}101@Component({102 selector: 'c-keep',103 template: 'KeepComponent',104})105export class KeepComponent {}106@Component({107 selector: 'c-mock',108 template: 'MockComponent',109})...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import { serviceCustomize } from 'ng-mocks';2import { MyService } from './my.service';3describe('MyService', () => {4 let service: MyService;5 beforeEach(() => {6 service = serviceCustomize({7 useValue: {8 getSomething: () => 'my value',9 },10 });11 });12 it('should return a value', () => {13 expect(service.getSomething()).toBe('my value');14 });15});

Full Screen

Using AI Code Generation

copy

Full Screen

1import { serviceCustomize } from 'ng-mocks';2import { MyService } from './my.service';3describe('MyService', () => {4 let service: MyService;5 beforeEach(() => {6 service = serviceCustomize({7 useValue: {8 myMethod: () => 42,9 },10 });11 });12 it('should be created', () => {13 expect(service).toBeTruthy();14 });15 it('should return 42', () => {16 expect(service.myMethod()).toBe(42);17 });18});19import { serviceCustomize } from 'ng-mocks';20import { MyService } from './my.service';21beforeEach(() => {22 serviceCustomize({23 useValue: {24 myMethod: () => 42,25 },26 });27});28import { serviceCustomize } from 'ng-mocks';29import { MyService } from './my.service';30export function mockServices() {31 serviceCustomize({32 useValue: {33 myMethod: () => 42,34 },35 });36}37Then, you can import the mockServices function in your test.ts file and call it:38import { mockServices } from './mocks';39beforeEach(() => {40 mockServices();41});

Full Screen

Using AI Code Generation

copy

Full Screen

1import { serviceCustomize } from 'ng-mocks';2import { Injectable } from '@angular/core';3import { HttpClient } from '@angular/common/http';4import { Observable } from 'rxjs';5@Injectable()6export class TestService {7 constructor(private http: HttpClient) {}8 getTest(): Observable<any> {9 }10}11import { serviceCustomize } from 'ng-mocks';12import { TestBed } from '@angular/core/testing';13import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';14import { TestService } from './test.service';15import { of } from 'rxjs';16describe('TestService', () => {17 let service: TestService;18 let httpMock: HttpTestingController;19 beforeEach(() => {20 TestBed.configureTestingModule({21 imports: [HttpClientTestingModule],22 });23 service = TestBed.inject(TestService);24 httpMock = TestBed.inject(HttpTestingController);25 });26 afterEach(() => {27 httpMock.verify();28 });29 it('should be created', () => {30 expect(service).toBeTruthy();31 });32 it('should return expected data', () => {33 serviceCustomize(TestService, {34 getTest: () => of({ id: 1, title: 'test' }),35 });36 service.getTest().subscribe((data) => {37 expect(data).toEqual({ id: 1, title: 'test' });38 });39 expect(req.request.method).toBe('GET');40 req.flush({ id: 1, title: 'test' });41 });42});

Full Screen

Using AI Code Generation

copy

Full Screen

1import { serviceCustomize } from 'ng-mocks';2import { MyService } from './my-service';3describe('test', () => {4 it('test', () => {5 const myService = serviceCustomize({6 useValue: {7 myMethod: () => 'myValue',8 },9 });10 expect(myService.myMethod()).toEqual('myValue');11 });12});13export class MyService {14 myMethod() {15 return 'myValue';16 }17}18import { MyService } from './my-service';19describe('MyService', () => {20 it('should create an instance', () => {21 expect(new MyService()).toBeTruthy();22 });23});24import { MyService } from './my-service';25describe('MyService', () => {26 it('should create an instance', () => {27 expect(new MyService()).toBeTruthy();28 });29});30import { MyService } from './my-service';31describe('MyService', () => {32 it('should create an instance', () => {33 expect(new MyService()).toBeTruthy();34 });35});36import { MyService } from './my-service';37describe('MyService', () => {38 it('should create an instance', () => {39 expect(new MyService()).toBeTruthy();40 });41});42import { MyService } from './my-service';43describe('MyService', () => {44 it('should create an instance', () => {45 expect(new MyService()).toBeTruthy();46 });47});48import { MyService } from './my-service';49describe('MyService', () => {50 it('should create an instance', () => {51 expect(new MyService()).toBeTruthy();52 });53});54import { MyService } from './my-service';55describe('MyService', () => {56 it('should create an instance', () => {57 expect(new MyService()).toBeTruthy();58 });59});60import { MyService } from './my-service';61describe('MyService', () => {62 it('should create an instance', () => {63 expect(new MyService()).toBeTruthy();64 });65});

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('AppComponent', () => {2 let component: AppComponent;3 let fixture: ComponentFixture<AppComponent>;4 beforeEach(async(() => {5 TestBed.configureTestingModule({6 })7 .compileComponents();8 }));9 beforeEach(() => {10 serviceSpy = jasmine.createSpyObj('AppService', ['getUsers']);11 fixture = TestBed.createComponent(AppComponent);12 component = fixture.componentInstance;13 fixture.detectChanges();14 service = TestBed.get(AppService);15 });16 it('should create', () => {17 expect(component).toBeTruthy();18 });19 it('should call getUsers', () => {20 serviceSpy.getUsers.and.returnValue(of([]));21 component.ngOnInit();22 expect(serviceSpy.getUsers).toHaveBeenCalled();23 });24});25export class AppService {26 getUsers() {27 return of([]);28 }29}30export class AppComponent implements OnInit {31 users: any;32 constructor(private appService: AppService) { }33 ngOnInit() {34 this.appService.getUsers()35 .subscribe(users => this.users = users);36 }37}38 <li *ngFor="let user of users">{{user}}</li>39describe('AppComponent', () => {40 let component: AppComponent;41 let fixture: ComponentFixture<AppComponent>;42 beforeEach(async(() => {43 TestBed.configureTestingModule({44 })

Full Screen

Using AI Code Generation

copy

Full Screen

1import { serviceCustomize } from 'ng-mocks';2describe('serviceCustomize', () => {3 it('should customize a service', () => {4 const spy = jasmine.createSpy();5 serviceCustomize({6 useValue: {7 method: () => spy(),8 },9 });10 TestBed.configureTestingModule({11 imports: [HttpClientTestingModule],12 });13 const service = TestBed.get(SomeService);14 service.method();15 expect(spy).toHaveBeenCalled();16 });17});

Full Screen

Using AI Code Generation

copy

Full Screen

1import { serviceCustomize } from 'ng-mocks';2import { MyService } from './my-service';3import { MyMockService } from './my-mock-service';4import { MyComponent } from './my-component';5describe('MyComponent', () => {6 let component: MyComponent;7 let fixture: ComponentFixture<MyComponent>;8 let myMockService: MyMockService;9 let myService: MyService;10 beforeEach(async(() => {11 myMockService = serviceCustomize(MyMockService, {12 myMethod: () => 'mocked',13 });14 TestBed.configureTestingModule({15 { provide: MyMockService, useValue: myMockService },16 }).compileComponents();17 }));18 beforeEach(() => {19 fixture = TestBed.createComponent(MyComponent);20 component = fixture.componentInstance;21 myService = TestBed.get(MyService);22 fixture.detectChanges();23 });24 it('should create', () => {25 expect(component).toBeTruthy();26 });27 it('should call myMethod of MyMockService', () => {28 component.ngOnInit();29 expect(myMockService.myMethod).toHaveBeenCalled();30 });31 it('should return the value of myMethod of MyMockService', () => {

Full Screen

Using AI Code Generation

copy

Full Screen

1import { serviceCustomize } from 'ng-mocks';2class MockService {3 public getMockData() {4 return 'mock data';5 }6}7serviceCustomize('MockService', MockService);8import { service } from 'ng-mocks';9describe('MockService', () => {10 let service: MockService;11 beforeEach(() => {12 service = service('MockService');13 });14 it('should return mock data', () => {15 expect(service.getMockData()).toBe('mock data');16 });17});18import { serviceCustomize } from 'ng-mocks';19serviceCustomize('MockService', () => {20 return {21 getMockData: () => 'mock data',22 };23});24import { service } from 'ng-mocks';25describe('MockService', () => {26 let service: MockService;27 beforeEach(() => {28 service = service('MockService');29 });30 it('should return mock data', () => {31 expect(service.getMockData()).toBe('mock data');32 });33});34import { serviceCustomize } from 'ng-mocks';35serviceCustomize('MockService', () => {36 return {37 getMockData: () => 'mock data',38 };39});40import { service } from 'ng-mocks';41describe('MockService', () => {42 let service: MockService;43 beforeEach(() => {44 service = service('MockService');45 });46 it('should return mock data', () => {47 expect(service.getMockData()).toBe('mock data');48 });49});50import { serviceCustomize } from 'ng-mocks';51serviceCustomize('MockService', () => {52 return {53 getMockData: () => 'mock data',54 };55});56import { service } from 'ng-mocks';57describe('MockService', () => {58 let service: MockService;59 beforeEach(() =>

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run ng-mocks automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful