How to use triggerUpdate method in ng-mocks

Best JavaScript code snippet using ng-mocks

globe.js

Source:globe.js Github

copy

Full Screen

1import { AmbientLight, DirectionalLight, Vector2 } from 'three';2import { CSS2DRenderer } from 'three/examples/jsm/renderers/CSS2DRenderer.js';34const THREE = {5 ...(window.THREE6 ? window.THREE // Prefer consumption from global THREE, if exists7 : { AmbientLight, DirectionalLight, Vector2 }8 ),9 CSS2DRenderer10};1112import ThreeGlobe from 'three-globe';13import ThreeRenderObjects from 'three-render-objects';1415import accessorFn from 'accessor-fn';16import Kapsule from 'kapsule';17import TWEEN from '@tweenjs/tween.js';1819import linkKapsule from './kapsule-link.js';2021//2223// Expose config from ThreeGlobe24const bindGlobe = linkKapsule('globe', ThreeGlobe);25const linkedGlobeProps = Object.assign(...[26 'globeImageUrl',27 'bumpImageUrl',28 'showGlobe',29 'showGraticules',30 'showAtmosphere',31 'atmosphereColor',32 'atmosphereAltitude',33 'globeMaterial',34 'onGlobeReady',35 'pointsData',36 'pointLat',37 'pointLng',38 'pointColor',39 'pointAltitude',40 'pointRadius',41 'pointResolution',42 'pointsMerge',43 'pointsTransitionDuration',44 'arcsData',45 'arcStartLat',46 'arcStartLng',47 'arcEndLat',48 'arcEndLng',49 'arcColor',50 'arcAltitude',51 'arcAltitudeAutoScale',52 'arcStroke',53 'arcCurveResolution',54 'arcCircularResolution',55 'arcDashLength',56 'arcDashGap',57 'arcDashInitialGap',58 'arcDashAnimateTime',59 'arcsTransitionDuration',60 'polygonsData',61 'polygonGeoJsonGeometry',62 'polygonCapColor',63 'polygonCapMaterial',64 'polygonSideColor',65 'polygonSideMaterial',66 'polygonStrokeColor',67 'polygonAltitude',68 'polygonCapCurvatureResolution',69 'polygonsTransitionDuration',70 'pathsData',71 'pathPoints',72 'pathPointLat',73 'pathPointLng',74 'pathPointAlt',75 'pathResolution',76 'pathColor',77 'pathStroke',78 'pathDashLength',79 'pathDashGap',80 'pathDashInitialGap',81 'pathDashAnimateTime',82 'pathTransitionDuration',83 'hexBinPointsData',84 'hexBinPointLat',85 'hexBinPointLng',86 'hexBinPointWeight',87 'hexBinResolution',88 'hexMargin',89 'hexTopCurvatureResolution',90 'hexTopColor',91 'hexSideColor',92 'hexAltitude',93 'hexBinMerge',94 'hexTransitionDuration',95 'hexPolygonsData',96 'hexPolygonGeoJsonGeometry',97 'hexPolygonColor',98 'hexPolygonAltitude',99 'hexPolygonResolution',100 'hexPolygonMargin',101 'hexPolygonCurvatureResolution',102 'hexPolygonsTransitionDuration',103 'tilesData',104 'tileLat',105 'tileLng',106 'tileAltitude',107 'tileWidth',108 'tileHeight',109 'tileUseGlobeProjection',110 'tileMaterial',111 'tileCurvatureResolution',112 'tilesTransitionDuration',113 'ringsData',114 'ringLat',115 'ringLng',116 'ringAltitude',117 'ringColor',118 'ringResolution',119 'ringMaxRadius',120 'ringPropagationSpeed',121 'ringRepeatPeriod',122 'labelsData',123 'labelLat',124 'labelLng',125 'labelAltitude',126 'labelRotation',127 'labelText',128 'labelSize',129 'labelTypeFace',130 'labelColor',131 'labelResolution',132 'labelIncludeDot',133 'labelDotRadius',134 'labelDotOrientation',135 'labelsTransitionDuration',136 'htmlElementsData',137 'htmlLat',138 'htmlLng',139 'htmlAltitude',140 'htmlElement',141 'htmlTransitionDuration',142 'objectsData',143 'objectLat',144 'objectLng',145 'objectAltitude',146 'objectThreeObject',147 'customLayerData',148 'customThreeObject',149 'customThreeObjectUpdate'150].map(p => ({ [p]: bindGlobe.linkProp(p)})));151const linkedGlobeMethods = Object.assign(...[152 'getGlobeRadius',153 'getCoords',154 'toGeoCoords'155].map(p => ({ [p]: bindGlobe.linkMethod(p)})));156157// Expose config from renderObjs158const bindRenderObjs = linkKapsule('renderObjs', ThreeRenderObjects);159const linkedRenderObjsProps = Object.assign(...[160 'width',161 'height',162 'backgroundColor',163 'backgroundImageUrl',164 'enablePointerInteraction'165].map(p => ({ [p]: bindRenderObjs.linkProp(p)})));166const linkedRenderObjsMethods = Object.assign(...[167 'postProcessingComposer'168].map(p => ({ [p]: bindRenderObjs.linkMethod(p)})));169170//171172export default Kapsule({173174 props: {175 onZoom: { triggerUpdate: false },176 onGlobeClick: { triggerUpdate: false },177 onGlobeRightClick: { triggerUpdate: false },178 pointLabel: { default: 'name', triggerUpdate: false },179 onPointClick: { triggerUpdate: false },180 onPointRightClick: { triggerUpdate: false },181 onPointHover: { triggerUpdate: false },182 arcLabel: { default: 'name', triggerUpdate: false },183 onArcClick: { triggerUpdate: false },184 onArcRightClick: { triggerUpdate: false },185 onArcHover: { triggerUpdate: false },186 polygonLabel: { default: 'name', triggerUpdate: false },187 onPolygonClick: { triggerUpdate: false },188 onPolygonRightClick: { triggerUpdate: false },189 onPolygonHover: { triggerUpdate: false },190 pathLabel: { default: 'name', triggerUpdate: false },191 onPathClick: { triggerUpdate: false },192 onPathRightClick: { triggerUpdate: false },193 onPathHover: { triggerUpdate: false },194 hexLabel: { triggerUpdate: false },195 onHexClick: { triggerUpdate: false },196 onHexRightClick: { triggerUpdate: false },197 onHexHover: { triggerUpdate: false },198 hexPolygonLabel: { triggerUpdate: false },199 onHexPolygonClick: { triggerUpdate: false },200 onHexPolygonRightClick: { triggerUpdate: false },201 onHexPolygonHover: { triggerUpdate: false },202 tileLabel: { default: 'name', triggerUpdate: false },203 onTileClick: { triggerUpdate: false },204 onTileRightClick: { triggerUpdate: false },205 onTileHover: { triggerUpdate: false },206 labelLabel: { triggerUpdate: false },207 onLabelClick: { triggerUpdate: false },208 onLabelRightClick: { triggerUpdate: false },209 onLabelHover: { triggerUpdate: false },210 objectLabel: { default: 'name', triggerUpdate: false },211 onObjectClick: { triggerUpdate: false },212 onObjectRightClick: { triggerUpdate: false },213 onObjectHover: { triggerUpdate: false },214 customLayerLabel: { default: 'name', triggerUpdate: false },215 onCustomLayerClick: { triggerUpdate: false },216 onCustomLayerRightClick: { triggerUpdate: false },217 onCustomLayerHover: { triggerUpdate: false },218 pointerEventsFilter: {219 default: () => true,220 triggerUpdate: false,221 onChange: (filterFn, state) => state.renderObjs.hoverFilter(obj => filterFn(obj, obj.__data))222 },223 lineHoverPrecision: {224 default: 0.2,225 triggerUpdate: false,226 onChange: (val, state) => state.renderObjs.lineHoverPrecision(val)227 },228 ...linkedGlobeProps,229 ...linkedRenderObjsProps230 },231232 methods: {233 pauseAnimation: function(state) {234 if (state.animationFrameRequestId !== null) {235 cancelAnimationFrame(state.animationFrameRequestId);236 state.animationFrameRequestId = null;237 }238 return this;239 },240 resumeAnimation: function(state) {241 if (state.animationFrameRequestId === null) {242 this._animationCycle();243 }244 return this;245 },246 _animationCycle(state) {247 // Frame cycle248 state.renderObjs.tick();249 state.animationFrameRequestId = requestAnimationFrame(this._animationCycle);250 },251 pointOfView: function(state, geoCoords = {}, transitionDuration = 0) {252 const curGeoCoords = getGeoCoords();253254 // Getter255 if (geoCoords.lat === undefined && geoCoords.lng === undefined && geoCoords.altitude === undefined) {256 return curGeoCoords;257 } else { // Setter258 const finalGeoCoords = Object.assign({}, curGeoCoords, geoCoords);259 ['lat', 'lng', 'altitude'].forEach(p => finalGeoCoords[p] = +finalGeoCoords[p]); // coerce coords to number260 261 if (!transitionDuration) { // no animation262 setCameraPos(finalGeoCoords);263 } else {264 // Avoid rotating more than 180deg longitude265 while ((curGeoCoords.lng - finalGeoCoords.lng) > 180) curGeoCoords.lng -= 360;266 while ((curGeoCoords.lng - finalGeoCoords.lng) < -180) curGeoCoords.lng += 360;267268 new TWEEN.Tween(curGeoCoords)269 .to(finalGeoCoords, transitionDuration)270 .easing(TWEEN.Easing.Cubic.InOut)271 .onUpdate(setCameraPos)272 .start();273 }274 return this;275 }276277 //278279 function getGeoCoords() {280 return state.globe.toGeoCoords(state.renderObjs.cameraPosition());281 }282283 function setCameraPos({ lat, lng, altitude }) {284 state.renderObjs.cameraPosition(state.globe.getCoords(lat, lng, altitude));285 }286 },287 getScreenCoords: (state, ...geoCoords) => {288 const cartesianCoords = state.globe.getCoords(...geoCoords);289 return state.renderObjs.getScreenCoords(cartesianCoords.x, cartesianCoords.y, cartesianCoords.z);290 },291 toGlobeCoords: (state, x, y) => {292 const globeIntersects = state.renderObjs.intersectingObjects(x, y).find(d => d.object.__globeObjType === 'globe');293 if (!globeIntersects) return null; // coords outside globe294295 const { lat, lng } = state.globe.toGeoCoords(globeIntersects.point);296 return { lat, lng };297 },298 scene: state => state.renderObjs.scene(), // Expose scene299 camera: state => state.renderObjs.camera(), // Expose camera300 renderer: state => state.renderObjs.renderer(), // Expose renderer301 controls: state => state.renderObjs.controls(), // Expose controls302 _destructor: function() {303 this.pauseAnimation();304 this.pointsData([]);305 this.arcsData([]);306 this.polygonsData([]);307 this.pathsData([]);308 this.hexBinPointsData([]);309 this.hexPolygonsData([]);310 this.tilesData([]);311 this.labelsData([]);312 this.htmlElementsData([]);313 this.objectsData([]);314 this.customLayerData([]);315 },316 ...linkedGlobeMethods,317 ...linkedRenderObjsMethods318 },319320 stateInit: ({ rendererConfig, waitForGlobeReady = true, ...globeInitConfig }) => {321 const globe = new ThreeGlobe({ waitForGlobeReady, ...globeInitConfig });322 return {323 globe,324 renderObjs: ThreeRenderObjects({325 controlType: 'orbit',326 rendererConfig,327 waitForLoadComplete: waitForGlobeReady,328 extraRenderers: [new THREE.CSS2DRenderer()] // Used in HTML elements layer329 })330 .skyRadius(globe.getGlobeRadius() * 500)331 .showNavInfo(false)332 }333 },334335 init: function(domNode, state) {336 // Wipe DOM337 domNode.innerHTML = '';338339 // Add relative container340 domNode.appendChild(state.container = document.createElement('div'));341 state.container.style.position = 'relative';342343 // Add renderObjs344 const roDomNode = document.createElement('div');345 state.container.appendChild(roDomNode);346 state.renderObjs(roDomNode);347348 // inject renderer size on three-globe349 state.globe.rendererSize(state.renderObjs.renderer().getSize(new THREE.Vector2()));350351 // set initial distance352 this.pointOfView({ altitude: 2.5 });353354 // calibrate orbit controls355 const globeR = state.globe.getGlobeRadius();356 const controls = state.renderObjs.controls();357 controls.minDistance = globeR * 1.01; // just above the surface358 setTimeout(() => controls.maxDistance = globeR * 100); // apply async after renderObjs sets maxDistance359 controls.enablePan = false;360 controls.enableDamping = true;361 controls.dampingFactor = 0.1;362 controls.rotateSpeed = 0.3;363 controls.zoomSpeed = 0.3;364 controls.addEventListener('change', () => {365 // adjust controls speed based on altitude366 const pov = this.pointOfView();367 controls.rotateSpeed = pov.altitude * 0.2; // Math.pow(pov.altitude + 1, 2) * 0.025;368 controls.zoomSpeed = (pov.altitude + 1) * 0.1; // Math.sqrt(pov.altitude) * 0.2;369370 // Update three-globe pov when camera moves, for proper hiding of elements371 state.globe.setPointOfView(state.renderObjs.camera().position);372373 state.onZoom && state.onZoom(pov);374 });375376 // config renderObjs377 const getGlobeObj = object => {378 let obj = object;379 // recurse up object chain until finding the globe object380 while (obj && !obj.hasOwnProperty('__globeObjType')) {381 obj = obj.parent;382 }383 return obj;384 };385386 const dataAccessors = {387 point: d => d,388 arc: d => d,389 polygon: d => d.data,390 path: d => d,391 hexbin: d => d,392 hexPolygon: d => d,393 tile: d => d,394 label: d => d,395 object: d => d,396 custom: d => d397 };398399 state.renderObjs400 .objects([ // Populate scene401 new THREE.AmbientLight(0xbbbbbb),402 new THREE.DirectionalLight(0xffffff, 0.6),403 state.globe404 ])405 .hoverOrderComparator((a, b) => {406 const aObj = getGlobeObj(a);407 const bObj = getGlobeObj(b);408409 // de-prioritize background / non-globe objects410 const isBackground = o => !o; // || o.__globeObjType === 'globe' || o.__globeObjType === 'atmosphere';411 return isBackground(aObj) - isBackground(bObj);412 })413 .tooltipContent(obj => {414 const objAccessors = {415 point: state.pointLabel,416 arc: state.arcLabel,417 polygon: state.polygonLabel,418 path: state.pathLabel,419 hexbin: state.hexLabel,420 hexPolygon: state.hexPolygonLabel,421 tile: state.tileLabel,422 label: state.labelLabel,423 object: state.objectLabel,424 custom: state.customLayerLabel425 };426427 const globeObj = getGlobeObj(obj);428 const objType = globeObj && globeObj.__globeObjType;429430 return globeObj && objType && objAccessors.hasOwnProperty(objType) && dataAccessors.hasOwnProperty(objType)431 ? accessorFn(objAccessors[objType])(dataAccessors[objType](globeObj.__data)) || ''432 : '';433 })434 .onHover(obj => {435 // Update tooltip and trigger onHover events436 const hoverObjFns = {437 point: state.onPointHover,438 arc: state.onArcHover,439 polygon: state.onPolygonHover,440 path: state.onPathHover,441 hexbin: state.onHexHover,442 hexPolygon: state.onHexPolygonHover,443 tile: state.onTileHover,444 label: state.onLabelHover,445 object: state.onObjectHover,446 custom: state.onCustomLayerHover447 };448449 const clickObjFns = {450 globe: state.onGlobeClick,451 point: state.onPointClick,452 arc: state.onArcClick,453 polygon: state.onPolygonClick,454 path: state.onPathClick,455 hexbin: state.onHexClick,456 hexPolygon: state.onHexPolygonClick,457 tile: state.onTileClick,458 label: state.onLabelClick,459 object: state.onObjectClick,460 custom: state.onCustomLayerClick461 };462463 let hoverObj = getGlobeObj(obj);464465 // ignore non-recognised obj types466 hoverObj && !hoverObjFns.hasOwnProperty(hoverObj.__globeObjType) && (hoverObj = null);467468 if (hoverObj !== state.hoverObj) {469 const prevObjType = state.hoverObj ? state.hoverObj.__globeObjType : null;470 const prevObjData = state.hoverObj ? dataAccessors[prevObjType](state.hoverObj.__data) : null;471 const objType = hoverObj ? hoverObj.__globeObjType : null;472 const objData = hoverObj ? dataAccessors[objType](hoverObj.__data) : null;473 if (prevObjType && prevObjType !== objType) {474 // Hover out475 hoverObjFns[prevObjType] && hoverObjFns[prevObjType](null, prevObjData);476 }477 if (objType) {478 // Hover in479 hoverObjFns[objType] && hoverObjFns[objType](objData, prevObjType === objType ? prevObjData : null);480 }481482 // set pointer if hovered object is clickable483 state.renderObjs.renderer().domElement.classList[(objType && clickObjFns[objType]) ? 'add' : 'remove']('clickable');484485 state.hoverObj = hoverObj;486 }487 })488 .onClick((obj, ev, point) => {489 if (!obj) return; // ignore background clicks490491 // Handle click events on objects492 const objFns = {493 globe: state.onGlobeClick,494 point: state.onPointClick,495 arc: state.onArcClick,496 polygon: state.onPolygonClick,497 path: state.onPathClick,498 hexbin: state.onHexClick,499 hexPolygon: state.onHexPolygonClick,500 tile: state.onTileClick,501 label: state.onLabelClick,502 object: state.onObjectClick,503 custom: state.onCustomLayerClick504 };505506 const globeObj = getGlobeObj(obj);507 const objType = globeObj.__globeObjType;508 if (globeObj && objFns.hasOwnProperty(objType) && objFns[objType]) {509 const args = [ev];510511 // include click coords512 if (objType === 'globe') {513 const { lat, lng } = this.toGeoCoords(point);514 args.unshift({ lat, lng });515 } else {516 args.push(this.toGeoCoords(point));517 }518519 dataAccessors.hasOwnProperty(objType) && args.unshift(dataAccessors[objType](globeObj.__data));520 objFns[objType](...args);521 }522 })523 .onRightClick((obj, ev, point) => {524 if (!obj) return; // ignore background clicks525526 // Handle right-click events527 const objFns = {528 globe: state.onGlobeRightClick,529 point: state.onPointRightClick,530 arc: state.onArcRightClick,531 polygon: state.onPolygonRightClick,532 path: state.onPathRightClick,533 hexbin: state.onHexRightClick,534 hexPolygon: state.onHexPolygonRightClick,535 tile: state.onTileRightClick,536 label: state.onLabelRightClick,537 object: state.onObjectRightClick,538 custom: state.onCustomLayerRightClick539 };540541 const globeObj = getGlobeObj(obj);542 const objType = globeObj.__globeObjType;543 if (globeObj && objFns.hasOwnProperty(objType) && objFns[objType]) {544 const args = [ev];545546 // include click coords547 if (objType === 'globe') {548 const { lat, lng } = this.toGeoCoords(point);549 args.unshift({ lat, lng });550 } else {551 args.push(this.toGeoCoords(point));552 }553554 dataAccessors.hasOwnProperty(objType) && args.unshift(dataAccessors[objType](globeObj.__data));555 objFns[objType](...args);556 }557 });558559 //560561 // Kick-off renderer562 this._animationCycle();563 } ...

Full Screen

Full Screen

source-provider.test.js

Source:source-provider.test.js Github

copy

Full Screen

...33 userUpdate(key, value) {34 this.updateSource(key, value);35 }36}37function triggerUpdate() {38 jest.advanceTimersByTime(100);39}40describe('source-provider.js', () => {41 describe('SourceProvider', () => {42 it('Fails to create a direct instance of SourceProvider', () => {43 expect(() => {44 new SourceProvider('Provider');45 }).toThrow('Cannot construct SourceProvider instances directly');46 });47 it(`Fails to create a SourceProvider that doesn't pass a providerName into the super constructor.`, () => {48 expect(() => {49 new FailProvider();50 }).toThrow(`The providerName needs to be passed into super() from your provider's constructor.`);51 });52 it(`Fails to create a SourceProvider that define a typeName`, () => {53 expect(() => {54 new FailProvider2();55 }).toThrow(`A typeName string must be defined.`);56 });57 58 it(`Fails to create a SourceProvider that doesn't pass settings into the super constructor.`, () => {59 expect(() => {60 new FailProvider3();61 }).toThrow(`settings must be passed into the super() from your provider's constructor.`);62 });63 let testProvider;64 let store;65 beforeEach(() => {66 jest.useFakeTimers();67 store = new Store();68 store.subscribe.mockReturnValue(() => {});69 store.subscribeAll.mockReturnValue(() => {});70 store.getRawSource.mockReturnValue({});71 store.getSource.mockReturnValue({});72 store.getSources.mockReturnValue({});73 testProvider = new TestProvider(store);74 });75 it(`does not call sourcesChanged if sources haven't been updated`, () => {76 triggerUpdate();77 expect(store.sourcesChanged).toHaveBeenCalledTimes(0);78 });79 it(`calls sourcesChanged if sources have been updated and after waiting a period of time`, () => {80 testProvider.updateSource('/a', 3);81 expect(store.sourcesChanged).toHaveBeenCalledTimes(0);82 triggerUpdate();83 expect(store.sourcesChanged).toHaveBeenCalledTimes(1);84 });85 it(`does not continue calling sourcesChanged after changes have been sent`, () => {86 testProvider.updateSource('/a', 3);87 triggerUpdate();88 expect(store.sourcesChanged).toHaveBeenCalledTimes(1);89 triggerUpdate();90 expect(store.sourcesChanged).toHaveBeenCalledTimes(1);91 });92 it(`calls sourcesChanged multiple times after multiple updates`, () => {93 testProvider.updateSource('/a', 3);94 triggerUpdate();95 expect(store.sourcesChanged).toHaveBeenCalledTimes(1);96 testProvider.updateSource('/a', 3);97 triggerUpdate();98 expect(store.sourcesChanged).toHaveBeenCalledTimes(2);99 });100 it('calls sourcesChanged with each updated source', () => {101 testProvider.updateSource('/a', 3);102 testProvider.updateSource('/b', true);103 triggerUpdate();104 expect(store.sourcesChanged).toHaveBeenCalledTimes(1);105 expect(store.sourcesChanged).toHaveBeenNthCalledWith(1, 'TestProvider', {106 '/a': 3,107 '/b': true108 });109 });110 it(`calls sourcesChanged with first and most recent updates`, () => {111 testProvider.updateSource('/a', 3);112 testProvider.updateSource('/a', 5);113 testProvider.updateSource('/a', 10);114 testProvider.updateSource('/a/b', 'c');115 triggerUpdate();116 expect(store.sourcesChanged).toHaveBeenCalledTimes(2);117 expect(store.sourcesChanged).toHaveBeenNthCalledWith(1, 'TestProvider', {118 '/a': 3,119 '/a/b': 'c'120 });121 expect(store.sourcesChanged).toHaveBeenNthCalledWith(2, 'TestProvider', {122 '/a': 10123 });124 });125 it(`does not call sourcesRemoved if sources haven't been removed`, () => {126 triggerUpdate();127 expect(store.sourcesRemoved).toHaveBeenCalledTimes(0);128 });129 it(`calls sourcesRemoved if sources have been removed and after waiting a period of time`, () => {130 testProvider.removeSource('/a');131 expect(store.sourcesRemoved).toHaveBeenCalledTimes(0);132 triggerUpdate();133 expect(store.sourcesRemoved).toHaveBeenCalledTimes(1);134 });135 it(`does not continue calling sourcesRemoved after removals have been sent`, () => {136 testProvider.removeSource('/a');137 triggerUpdate();138 expect(store.sourcesRemoved).toHaveBeenCalledTimes(1);139 triggerUpdate();140 expect(store.sourcesRemoved).toHaveBeenCalledTimes(1);141 });142 it(`calls sourcesRemoved multiple times after multiple removals`, () => {143 testProvider.removeSource('/a');144 triggerUpdate();145 expect(store.sourcesRemoved).toHaveBeenCalledTimes(1);146 testProvider.removeSource('/a');147 triggerUpdate();148 expect(store.sourcesRemoved).toHaveBeenCalledTimes(2);149 });150 it('calls sourcesRemoved with each removed source', () => {151 testProvider.removeSource('/a');152 testProvider.removeSource('/b');153 triggerUpdate();154 expect(store.sourcesRemoved).toHaveBeenCalledTimes(1);155 expect(store.sourcesRemoved).toHaveBeenNthCalledWith(1, 'TestProvider', [156 '/a', '/b' 157 ]);158 });159 it(`calls sourcesChanged and sourcesRemoved in order of when they were triggered`, () => {160 161 let mockUpdates = {162 '/a': [],163 '/b': [],164 '/c': [],165 '/d': [],166 '/e': [],167 '/f': [],168 '/g': [],169 '/h': []170 };171 store.sourcesChanged.mockImplementation((_, changes) => {172 for (let key in changes) {173 mockUpdates[key].push('change');174 }175 });176 store.sourcesRemoved.mockImplementation((_, removals) => {177 removals.forEach(removal => {178 mockUpdates[removal].push('removal');179 });180 });181 testProvider.updateSource('/a', 1);182 testProvider.updateSource('/a', 2);183 testProvider.updateSource('/a', 3);184 testProvider.updateSource('/b', 1);185 testProvider.updateSource('/b', 2);186 testProvider.removeSource('/b');187 testProvider.updateSource('/c', 1);188 testProvider.removeSource('/c');189 testProvider.updateSource('/c', 2);190 testProvider.updateSource('/d', 1);191 testProvider.removeSource('/d');192 testProvider.removeSource('/d');193 testProvider.removeSource('/e');194 testProvider.updateSource('/e', 2);195 testProvider.updateSource('/e', 3);196 testProvider.removeSource('/f');197 testProvider.updateSource('/f', 2);198 testProvider.removeSource('/f');199 testProvider.removeSource('/g');200 testProvider.removeSource('/g');201 testProvider.updateSource('/g', 2);202 testProvider.removeSource('/h');203 testProvider.removeSource('/h');204 testProvider.removeSource('/h');205 triggerUpdate();206 expect(mockUpdates).toEqual({207 '/a': ['change', 'change'],208 '/b': ['change', 'removal'],209 '/c': ['change', 'change'],210 '/d': ['change', 'removal'],211 '/e': ['removal', 'change'],212 '/f': ['removal', 'removal'],213 '/g': ['removal', 'change'],214 '/h': ['removal', 'removal']215 });216 });217 it(`clears sources when clearSources is called`, () => {218 testProvider.clearSources();219 expect(store.clearSources).toHaveBeenCalledTimes(1);220 expect(store.clearSources).toHaveBeenNthCalledWith(1, 'TestProvider');221 });222 it(`clears sources after a timeout`, () => {223 testProvider.clearSourcesWithTimeout(2000);224 jest.advanceTimersByTime(1500);225 expect(store.clearSources).toHaveBeenCalledTimes(0);226 jest.advanceTimersByTime(1500);227 expect(store.clearSources).toHaveBeenCalledTimes(1);228 });229 it(`stops sources from clearing if sources are updated before timeout expires`, () => {230 testProvider.clearSourcesWithTimeout(2000);231 jest.advanceTimersByTime(1500);232 expect(store.clearSources).toHaveBeenCalledTimes(0);233 testProvider.updateSource('/a', 1);234 jest.advanceTimersByTime(1500);235 expect(store.clearSources).toHaveBeenCalledTimes(0);236 });237 it(`makes updates immediately when clearSources is called`, () => {238 testProvider.updateSource('/a', 1);239 testProvider.clearSources();240 expect(store.sourcesChanged).toHaveBeenCalledTimes(1);241 expect(store.sourcesChanged).toHaveBeenNthCalledWith(1, 'TestProvider', {242 '/a': 1243 });244 testProvider.updateSource('/a', 2);245 triggerUpdate();246 expect(store.sourcesChanged).toHaveBeenCalledTimes(2);247 expect(store.sourcesChanged).toHaveBeenNthCalledWith(2, 'TestProvider', {248 '/a': 2249 });250 testProvider.updateSource('/a', 1);251 testProvider.updateSource('/a', 2);252 testProvider.clearSources(() => {253 expect(store.sourcesChanged).toHaveBeenCalledTimes(4);254 triggerUpdate();255 expect(store.sourcesChanged).toHaveBeenCalledTimes(4);256 });257 jest.advanceTimersByTime(0);258 });259 it('subscribes to a particular source when subscribe is called', () => {260 const mockCallback = jest.fn();261 const cancel = testProvider.subscribe('/a', mockCallback, true);262 expect(cancel).toEqual(expect.any(Function));263 expect(store.subscribe).toHaveBeenCalledTimes(1);264 expect(store.subscribe).toHaveBeenNthCalledWith(1, 'TestProvider', '/a', mockCallback, true);265 });266 it('subscribes to all sources when subscribeAll is called', () => {267 const mockCallback = jest.fn();268 const cancel = testProvider.subscribeAll( mockCallback, true);269 expect(cancel).toEqual(expect.any(Function));270 expect(store.subscribeAll).toHaveBeenCalledTimes(1);271 expect(store.subscribeAll).toHaveBeenNthCalledWith(1, 'TestProvider', mockCallback, true);272 });273 it('gets a source when getSource is called', () => {274 const source = testProvider.getSource('/a');275 expect(source).toEqual({});276 expect(store.getSource).toHaveBeenCalledTimes(1);277 expect(store.getSource).toHaveBeenNthCalledWith(1, 'TestProvider', '/a');278 });279 it('gets a raw source when getRawSource is called', () => {280 const rawSource = testProvider.getRawSource('/a');281 expect(rawSource).toEqual({});282 expect(store.getRawSource).toHaveBeenCalledTimes(1);283 expect(store.getRawSource).toHaveBeenNthCalledWith(1, 'TestProvider', '/a');284 });285 it('gets all sources when getSources is called', () => {286 const allSources = testProvider.getSources();287 expect(allSources).toEqual({});288 expect(store.getSources).toHaveBeenCalledTimes(1);289 expect(store.getSources).toHaveBeenNthCalledWith(1, 'TestProvider');290 });291 it('gets the name of a type when getType is called', () => {292 expect(testProvider.getType('hello')).toBe('string');293 expect(testProvider.getType(10)).toBe('number');294 expect(testProvider.getType(false)).toBe('boolean');295 expect(testProvider.getType([1,2,3])).toBe('Array');296 expect(testProvider.getType(null)).toBe('null');297 expect(testProvider.getType(undefined)).toBe(null);298 });299 300 it('no longer sends updates when _disconnect is called', () => {301 testProvider._disconnect();302 testProvider.updateSource('/a', 3);303 testProvider.updateSource('/b', true);304 triggerUpdate();305 expect(store.sourcesChanged).toHaveBeenCalledTimes(0);306 });307 });...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1import { sleep, oppositeColor, opponentColor } from './helpers';2import { siteParser } from './parser';3import { position, replay, replayFen, gameState } from './game';4import { controlledSquares, drawControlledSquares } from './vision';5import { createOverlay, drawEvalBar, drawArrow, drawSlider, drawECO, drawSquare, drawTextBelow } from './draw';6import { playMove, state, stockfish } from './engine';7import { Shortcuts } from 'shortcuts';8import { eco } from './eco';9const main = async () => {10 try {11 const parser = siteParser(window.location.host);12 // Wait for the necessary elements for the parser before continuing13 console.log('Waiting for game');14 while (true) {15 if (parser.isReady()) {16 break;17 }18 await sleep(500);19 }20 gameState.overlaySelector = parser.getOverlay();21 gameState.mySide = parser.getSide();22 const shortcuts = new Shortcuts();23 shortcuts.add([24 {25 shortcut: 'q q e e',26 handler: () => {27 gameState.enableArrow = !gameState.enableArrow;28 gameState.triggerUpdate = true;29 },30 },31 ]);32 shortcuts.add([33 {34 shortcut: 'w w d d',35 handler: () => {36 gameState.enableMultiPV = !gameState.enableMultiPV;37 gameState.triggerUpdate = true;38 },39 },40 ]);41 console.log('Starting main loop');42 while (true) {43 await sleep(16.667);44 const parsedSide = parser.getSide();45 const moves = parser.parseMoves();46 if (typeof parser.getFen !== 'undefined') {47 var parsedFen = parser.getFen(parsedSide);48 if (parsedFen != null) {49 gameState.parsedFen = parsedFen;50 }51 }52 const width = gameState.overlaySelector.clientWidth;53 if (width === 0) {54 gameState.overlaySelector = parser.getOverlay();55 }56 // If the number of moves, the mySide or the size of the board changes, redraw all the things!57 if (58 gameState.triggerUpdate ||59 moves.length !== gameState.numOfMoves ||60 gameState.mySide !== parsedSide ||61 gameState.boardWidth !== width ||62 gameState.fen !== gameState.parsedFen ||63 state.triggerUpdate64 ) {65 if (gameState.mySide !== parsedSide) {66 console.log('Switched sides to ' + parsedSide);67 }68 gameState.triggerUpdate = false;69 gameState.numOfMoves = moves.length;70 gameState.mySide = parsedSide;71 gameState.boardWidth = width;72 gameState.fen = gameState.parsedFen;73 if (gameState.numOfMoves) {74 replay(moves);75 } else if (gameState.fen) {76 replayFen(gameState.fen);77 }78 // Post position to the engine only if the engine didn't trigger the update79 if (!state.triggerUpdate) {80 playMove(position.fen(), gameState.depth);81 }82 createOverlay('cv-overlay', gameState.overlaySelector, gameState.mySide, parser.zIndex, false, false);83 let textOverlay = createOverlay('cv-overlay-text', gameState.overlaySelector, gameState.mySide, 99999, true, false);84 let overlayElement = createOverlay('cv-overlay-svg', gameState.overlaySelector, gameState.mySide, 10000, false, true);85 let positionFen = position.fen().slice(0, -4);86 if (positionFen in eco) {87 gameState.lastKnownPosition = eco[positionFen].name;88 }89 drawECO(textOverlay, 'cv-eco', gameState.lastKnownPosition);90 if (gameState.numOfMoves || gameState.fen) {91 const squares = controlledSquares(position);92 drawControlledSquares(squares, gameState.mySide, gameState.enableArrow);93 } else {94 document.querySelector('#cv-overlay').style.border = '1px dashed hsl(140, 100%, 50%)';95 }96 if (state.triggerUpdate) {97 // console.log('Engine update');98 // Eval bar should only be rendered if the engine updated its state99 drawEvalBar('cv-overlay', state.score, gameState.mySide, state.turn);100 if (gameState.enableArrow || gameState.enableMultiPV) {101 drawSlider('cv-overlay', 'cv-depth', gameState.depth, 1, 16, '0px');102 drawTextBelow('cv-overlay', 'cv-depth-text', '0px', `Depth ${gameState.depth}`);103 document.getElementById('cv-depth').addEventListener('change', e => {104 gameState.depth = parseInt(e.target.value);105 console.log('Depth: ' + gameState.depth);106 localStorage.setItem('cv-depth', gameState.depth.toString());107 gameState.triggerUpdate = true;108 });109 drawSlider('cv-overlay', 'cv-multi-pv', state.multiPV, 1, 6, 'calc(37% - 60px)');110 drawTextBelow('cv-overlay', 'cv-multi-pv-text', 'calc(37% - 60px)', `Multi PV ${state.multiPV}`);111 document.getElementById('cv-multi-pv').addEventListener('change', e => {112 state.multiPV = parseInt(e.target.value);113 stockfish.postMessage('setoption name MultiPV value ' + state.multiPV);114 stockfish.postMessage('isready');115 console.log('MultiPV: ' + state.multiPV);116 localStorage.setItem('cv-multi-pv', state.multiPV.toString());117 gameState.triggerUpdate = true;118 });119 }120 if (gameState.enableArrow) {121 drawArrow(122 overlayElement,123 state.bestMove,124 opponentColor(state.turn, gameState.mySide),125 gameState.boardWidth,126 gameState.mySide127 );128 drawArrow(129 overlayElement,130 state.ponder,131 opponentColor(oppositeColor(state.turn), gameState.mySide),132 gameState.boardWidth,133 gameState.mySide134 );135 }136 if (gameState.enableMultiPV) {137 for (var square of Object.values(state.multiPVSquares)) {138 drawSquare(square.slice(0, 2), { border: `2px solid hsl(280, 100%, 50%)` });139 }140 state.multiPVSquares = {};141 }142 }143 state.triggerUpdate = false;144 }145 }146 } catch (e) {147 console.error(e);148 }149};...

Full Screen

Full Screen

user-graph.ts

Source:user-graph.ts Github

copy

Full Screen

...25 this.triggerUpdate = triggerUpdate26 }27 public set colorHex (value: string) {28 this.vertex.colorHex = value29 this.triggerUpdate(this.vertex)30 }31 public set highlighted (value: boolean) {32 this.vertex.highlighted = value33 this.triggerUpdate(this.vertex)34 }35}36export class Edge {37 private edge: InternalEdge38 private triggerUpdate: (edge: InternalEdge) => void39 constructor (edge: InternalEdge, triggerUpdate: (v: InternalEdge) => void) {40 this.edge = edge41 this.triggerUpdate = triggerUpdate42 }43 public set colorHex (value: string) {44 this.edge.colorHex = value45 this.triggerUpdate(this.edge)46 }47 public set highlighted (value: boolean) {48 this.edge.highlighted = value49 this.triggerUpdate(this.edge)50 }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import { triggerUpdate } from 'ng-mocks';2import { TestBed } from '@angular/core/testing';3import { AppComponent } from './app.component';4describe('AppComponent', () => {5 beforeEach(async () => {6 await TestBed.configureTestingModule({7 }).compileComponents();8 });9 it('should update the component', () => {10 const fixture = TestBed.createComponent(AppComponent);11 const component = fixture.componentInstance;12 component.value = 'test';13 triggerUpdate(fixture);14 expect(component.value).toBe('test');15 });16});17import { Component } from '@angular/core';18@Component({19 template: '<div>{{ value }}</div>',20})21export class AppComponent {22 public value = 'test';23}24import { TestBed } from '@angular/core/testing';25import { AppComponent } from './app.component';26describe('AppComponent', () => {27 beforeEach(async () => {28 await TestBed.configureTestingModule({29 }).compileComponents();30 });31 it('should create the app', () => {32 const fixture = TestBed.createComponent(AppComponent);33 const app = fixture.componentInstance;34 expect(app).toBeTruthy();35 });36 it(`should have as title 'ng-mocks-demo'`, () => {37 const fixture = TestBed.createComponent(AppComponent);38 const app = fixture.componentInstance;39 expect(app.value).toEqual('test');40 });41 it('should render title', () => {42 const fixture = TestBed.createComponent(AppComponent);43 fixture.detectChanges();44 const compiled = fixture.nativeElement as HTMLElement;45 expect(compiled.querySelector('div')?.textContent).toContain('test');46 });47});48<div>{{ value }}</div>49div {50 color: red;51}52import { NgModule } from '@angular/core';53import { BrowserModule } from '@angular/platform-browser';54import { AppComponent } from './app.component';55@NgModule({56 imports: [BrowserModule],57})58export class AppModule {}59module.exports = function (config) {60 config.set({61 require('karma-jasmine'),62 require('karma-chrome-launcher'),

Full Screen

Using AI Code Generation

copy

Full Screen

1import { triggerUpdate } from 'ng-mocks';2import { triggerUpdate } from 'ng-mocks';3import { triggerUpdate } from 'ng-mocks';4import { triggerUpdate } from 'ng-mocks';5import { triggerUpdate } from 'ng-mocks';6import { triggerUpdate } from 'ng-mocks';7import { triggerUpdate } from 'ng-mocks';8import { triggerUpdate } from 'ng-mocks';9import { triggerUpdate } from 'ng-mocks';10import { triggerUpdate } from 'ng-mocks';11import { triggerUpdate } from 'ng-mocks';12import { triggerUpdate } from 'ng-mocks';13import { triggerUpdate } from 'ng-mocks';14import { triggerUpdate } from 'ng-mocks';15import { triggerUpdate } from 'ng-mocks';16import { triggerUpdate } from 'ng-mocks';17import { triggerUpdate } from 'ng-mocks';18import { triggerUpdate } from 'ng-mocks';19import { triggerUpdate } from 'ng-mocks';20import { triggerUpdate } from 'ng

Full Screen

Using AI Code Generation

copy

Full Screen

1const { MockBuilder, MockRender, ngMocks } = require('ng-mocks');2describe('MyComponent', () => {3 beforeEach(() => MockBuilder(MyComponent));4 it('should update', () => {5 const fixture = MockRender(MyComponent);6 ngMocks.triggerUpdate(fixture);7 });8});9import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';10describe('MyComponent', () => {11 beforeEach(() => MockBuilder(MyComponent));12 it('should update', () => {13 const fixture = MockRender(MyComponent);14 ngMocks.triggerUpdate(fixture);15 });16});17import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';18describe('MyComponent', () => {19 beforeEach(() => MockBuilder(MyComponent));20 it('should update', () => {21 const fixture = MockRender(MyComponent);22 ngMocks.triggerUpdate(fixture);23 });24});25import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';26describe('MyComponent', () => {27 beforeEach(() => MockBuilder(MyComponent));28 it('should update', () => {29 const fixture = MockRender(MyComponent);30 ngMocks.triggerUpdate(fixture);31 });32});33import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';34describe('MyComponent', () => {35 beforeEach(() => MockBuilder(MyComponent));36 it('should update', () => {37 const fixture = MockRender(MyComponent);38 ngMocks.triggerUpdate(fixture);39 });40});41import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';42describe('MyComponent', () => {43 beforeEach(() => MockBuilder(MyComponent));44 it('should update', () => {45 const fixture = MockRender(MyComponent);46 ngMocks.triggerUpdate(fixture);47 });48});49import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';

Full Screen

Using AI Code Generation

copy

Full Screen

1import { triggerUpdate } from 'ng-mocks';2triggerUpdate(fixture);3import { triggerUpdate } from 'ng-mocks';4triggerUpdate(fixture);5import { triggerUpdate } from 'ng-mocks';6triggerUpdate(fixture);7import { triggerUpdate } from 'ng-mocks';8triggerUpdate(fixture);9import { triggerUpdate } from 'ng-mocks';10triggerUpdate(fixture);11import { triggerUpdate } from 'ng-mocks';12triggerUpdate(fixture);13import { triggerUpdate } from 'ng-mocks';14triggerUpdate(fixture);15import { triggerUpdate } from 'ng-mocks';16triggerUpdate(fixture);17import { triggerUpdate } from 'ng-mocks';18triggerUpdate(fixture);19import { triggerUpdate } from 'ng-mocks';20triggerUpdate(fixture);21import { triggerUpdate } from 'ng-mocks';22triggerUpdate(fixture);23import { triggerUpdate } from 'ng-mocks';24triggerUpdate(fixture);25import { triggerUpdate } from 'ng-mocks';26triggerUpdate(fixture);27import { triggerUpdate } from 'ng-mocks';28triggerUpdate(fixture);29import { triggerUpdate } from 'ng-mocks';30triggerUpdate(fixture

Full Screen

Using AI Code Generation

copy

Full Screen

1import { triggerUpdate } from 'ng-mocks';2describe('test', () => {3 it('should be able to trigger update', () => {4 const fixture = TestBed.createComponent(TestComponent);5 fixture.detectChanges();6 triggerUpdate(fixture);7 expect(true).toBe(true);8 });9});

Full Screen

Using AI Code Generation

copy

Full Screen

1import { triggerUpdate } from 'ng-mocks';2triggerUpdate(fixture);3import { triggerUpdate } from 'ng-mocks';4triggerUpdate(fixture);5import { triggerEvent } from 'ng-mocks';6triggerEvent(element, 'click');7import { triggerEvent } from 'ng-mocks';8triggerEvent(element, 'click');9import { triggerInput } from 'ng-mocks';10triggerInput(element, 'test');11import { triggerInput } from 'ng-mocks';12triggerInput(element, 'test');13import { triggerClick } from 'ng-mocks';14triggerClick(element);15import { triggerClick } from 'ng-mocks';16triggerClick(element);17import { triggerKeyDown } from 'ng-mocks';18triggerKeyDown(element, 'ArrowDown');19import { triggerKeyDown } from 'ng-mocks';20triggerKeyDown(element, 'ArrowDown');21import { triggerKeyUp } from 'ng-mocks';22triggerKeyUp(element, 'ArrowDown');23import { triggerKeyUp } from 'ng-mocks';24triggerKeyUp(element, 'ArrowDown');

Full Screen

Using AI Code Generation

copy

Full Screen

1triggerUpdate(fixture, {value: 'some value'});2triggerClick(fixture, 'button');3triggerUpdate(fixture, {value: 'some value'});4triggerClick(fixture, 'button');5triggerUpdate(fixture, {value: 'some value'});6triggerClick(fixture, 'button');7I have also tried changing the import statement to import { triggerUpdate, triggerClick } from '@ngneat/spectator' but then I am getting the following error:8import { triggerUpdate, triggerClick } from 'ng-mocks';9I have also tried changing the import statement to import { triggerUpdate, triggerClick } from '@ngneat/spectator' but then I am getting the following error:10import { triggerUpdate, triggerClick } from 'ng-mocks

Full Screen

Using AI Code Generation

copy

Full Screen

1it('should trigger update method', () => {2 const fixture = ngMocks.findInstance(TestComponent);3 spyOn(fixture, 'triggerUpdate');4 expect(fixture.triggerUpdate).toHaveBeenCalled();5});6export class TestComponent {7 public triggerUpdate() {8 }9}

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