Best JavaScript code snippet using ng-mocks
game-controller.js
Source:game-controller.js
1'use strict';2const ServerConfig = require('../configs/server-config');3const AdminService = require('../services/admin-service');4const BoardOccupancyService = require('../services/board-occupancy-service');5const BotDirectionService = require('../services/bot-direction-service');6const FoodService = require('../services/food-service');7const GameControlsService = require('../services/game-controls-service');8const ImageService = require('../services/image-service');9const NameService = require('../services/name-service');10const NotificationService = require('../services/notification-service');11const PlayerService = require('../services/player-service');12const Coordinate = require('../models/coordinate');13const PlayerContainer = require('../models/player-container');14const PlayerStatBoard = require('../models/player-stat-board');15class GameController {16 constructor() {17 // Model Containers18 this.playerContainer = new PlayerContainer();19 this.playerStatBoard = new PlayerStatBoard();20 // Services21 this.nameService = new NameService();22 this.boardOccupancyService = new BoardOccupancyService();23 this.notificationService = new NotificationService();24 this.botDirectionService = new BotDirectionService(this.boardOccupancyService);25 this.foodService = new FoodService(this.playerStatBoard, this.boardOccupancyService,26 this.nameService, this.notificationService);27 this.imageService = new ImageService(this.playerContainer, this.playerStatBoard, this.notificationService);28 this.playerService = new PlayerService(this.playerContainer, this.playerStatBoard, this.boardOccupancyService,29 this.imageService, this.nameService, this.notificationService, this.runGameCycle.bind(this));30 this.adminService = new AdminService(this.playerContainer, this.foodService, this.nameService,31 this.notificationService, this.playerService);32 this.playerService.init(this.adminService.getPlayerStartLength.bind(this.adminService));33 }34 // Listen for Socket IO events35 listen(io) {36 this.notificationService.setSockets(io.sockets);37 const self = this;38 io.sockets.on(ServerConfig.IO.DEFAULT_CONNECTION, socket => {39 socket.on(ServerConfig.IO.INCOMING.CANVAS_CLICKED, self._canvasClicked.bind(self, socket));40 socket.on(ServerConfig.IO.INCOMING.KEY_DOWN, self._keyDown.bind(self, socket.id));41 // Player Service42 socket.on(ServerConfig.IO.INCOMING.NEW_PLAYER,43 self.playerService.addPlayer.bind(self.playerService, socket));44 socket.on(ServerConfig.IO.INCOMING.NAME_CHANGE,45 self.playerService.changePlayerName.bind(self.playerService, socket));46 socket.on(ServerConfig.IO.INCOMING.COLOR_CHANGE,47 self.playerService.changeColor.bind(self.playerService, socket));48 socket.on(ServerConfig.IO.INCOMING.JOIN_GAME,49 self.playerService.playerJoinGame.bind(self.playerService, socket.id));50 socket.on(ServerConfig.IO.INCOMING.SPECTATE_GAME,51 self.playerService.playerSpectateGame.bind(self.playerService, socket.id));52 socket.on(ServerConfig.IO.INCOMING.DISCONNECT,53 self.playerService.disconnectPlayer.bind(self.playerService, socket.id));54 // Image Service55 socket.on(ServerConfig.IO.INCOMING.CLEAR_UPLOADED_BACKGROUND_IMAGE,56 self.imageService.clearBackgroundImage.bind(self.imageService, socket.id));57 socket.on(ServerConfig.IO.INCOMING.BACKGROUND_IMAGE_UPLOAD,58 self.imageService.updateBackgroundImage.bind(self.imageService, socket.id));59 socket.on(ServerConfig.IO.INCOMING.CLEAR_UPLOADED_IMAGE,60 self.imageService.clearPlayerImage.bind(self.imageService, socket.id));61 socket.on(ServerConfig.IO.INCOMING.IMAGE_UPLOAD,62 self.imageService.updatePlayerImage.bind(self.imageService, socket.id));63 // Admin Service64 socket.on(ServerConfig.IO.INCOMING.BOT_CHANGE,65 self.adminService.changeBots.bind(self.adminService, socket.id));66 socket.on(ServerConfig.IO.INCOMING.FOOD_CHANGE,67 self.adminService.changeFood.bind(self.adminService, socket.id));68 socket.on(ServerConfig.IO.INCOMING.SPEED_CHANGE,69 self.adminService.changeSpeed.bind(self.adminService, socket.id));70 socket.on(ServerConfig.IO.INCOMING.START_LENGTH_CHANGE,71 self.adminService.changeStartLength.bind(self.adminService, socket.id));72 });73 }74 runGameCycle() {75 // Pause and reset the game if there aren't any players76 if (this.playerContainer.getNumberOfPlayers() - this.adminService.getBotIds().length === 0) {77 console.log('Game Paused');78 this.boardOccupancyService.initializeBoard();79 this.adminService.resetGame();80 this.nameService.reinitialize();81 this.imageService.resetBackgroundImage();82 this.foodService.reinitialize();83 this.playerContainer.reinitialize();84 this.playerStatBoard.reinitialize();85 return;86 }87 // Change bots' directions88 for (const botId of this.adminService.getBotIds()) {89 const bot = this.playerContainer.getPlayer(botId);90 if (Math.random() <= ServerConfig.BOT_CHANGE_DIRECTION_PERCENT) {91 this.botDirectionService.changeToRandomDirection(bot);92 }93 this.botDirectionService.changeDirectionIfInDanger(bot);94 }95 this.playerService.movePlayers();96 this.playerService.handlePlayerCollisions();97 this.playerService.respawnPlayers();98 this.foodService.consumeAndRespawnFood(this.playerContainer);99 const gameState = {100 players: this.playerContainer,101 food: this.foodService.getFood(),102 playerStats: this.playerStatBoard,103 walls: this.boardOccupancyService.getWallCoordinates(),104 speed: this.adminService.getGameSpeed(),105 numberOfBots: this.adminService.getBotIds().length,106 startLength: this.adminService.getPlayerStartLength(),107 };108 this.notificationService.broadcastGameState(gameState);109 setTimeout(this.runGameCycle.bind(this), 1000 / this.adminService.getGameSpeed());110 }111 /*******************************112 * socket.io handling methods *113 *******************************/114 _canvasClicked(socket, x, y) {115 const player = this.playerContainer.getPlayer(socket.id);116 const coordinate = new Coordinate(x, y);117 if (this.boardOccupancyService.isPermanentWall(coordinate)) {118 return;119 }120 if (this.boardOccupancyService.isWall(coordinate)) {121 this.boardOccupancyService.removeWall(coordinate);122 this.notificationService.broadcastNotification(`${player.name} has removed a wall`, player.color);123 } else {124 this.boardOccupancyService.addWall(coordinate);125 this.notificationService.broadcastNotification(`${player.name} has added a wall`, player.color);126 }127 }128 _keyDown(playerId, keyCode) {129 GameControlsService.handleKeyDown(this.playerContainer.getPlayer(playerId), keyCode);130 }131}...
monitor-data.js
Source:monitor-data.js
1/**2 * Api service for the monitor widget3 */4(function () {5 'use strict';6 angular7 .module(HygieiaConfig.module + '.core')8 .factory('monitorData', monitorData);9 function monitorData($http) {10 var monitorRoute = '/api/dashboard/';11 var serviceRoute = '/api/service/';12 var testingDetailRoute = 'test-data/monitor.json';13 var testingSearchRoute = 'test-data/monitor_config.json';14 var mappedStatusValues = {15 1: 'Ok',16 2: 'Warning',17 3: 'Alert'18 };19 return {20 details: details,21 search: search,22 createService: createService,23 updateService: updateService,24 refreshService: refreshService,25 deleteService: deleteService,26 createDependentService: createDependentService,27 deleteDependentService: deleteDependentService28 };29 // helper methods30 function getBaseRoute(dashboardId) {31 return monitorRoute + dashboardId + '/';32 }33 function getServiceRoute(dashboardId) {34 return getBaseRoute(dashboardId) + 'service/';35 }36 function getDependentServiceRoute(dashboardId) {37 return getBaseRoute(dashboardId) + 'dependent-service/';38 }39 // get all registered services40 function search() {41 return $http.get(HygieiaConfig.local ? testingSearchRoute : serviceRoute)42 .then(function (response) {43 return response.data;44 });45 }46 // get services for a given dashboard47 function details(dashboardId) {48 return $http.get(HygieiaConfig.local ? testingDetailRoute : getServiceRoute(dashboardId))49 .then(function (response) {50 return response.data;51 });52 }53 // add a new service name. name must be sent with quotes around it54 function createService(dashboardId, name, url) {55 var postData = {56 name: name,57 url: url58 }59 return $http.post(HygieiaConfig.local ? testingDetailRoute : getServiceRoute(dashboardId), JSON.stringify(postData))60 .then(function (response) {61 return response.data;62 });63 }64 function updateService(dashboardId, service) {65 // create a copy so we don't modify the original66 service = angular.copy(service);67 var serviceId = service.id;68 if (serviceId) {69 delete service.id;70 }71 // try to map the status value back to what the api expects72 service.status = mappedStatusValues[service.status] || service.status;73 return $http.put(HygieiaConfig.local ? testingDetailRoute : getServiceRoute(dashboardId) + serviceId, service)74 .then(function (response) {75 return response.data;76 });77 }78 function refreshService(dashboardId, service) {79 // create a copy so we don't modify the original80 service = angular.copy(service);81 var serviceId = service.id;82 if (serviceId) {83 delete service.id;84 }85 // try to map the status value back to what the api expects86 service.status = mappedStatusValues[service.status] || service.status;87 return $http.get(HygieiaConfig.local ? testingDetailRoute : getServiceRoute(dashboardId) + serviceId, service)88 .then(function (response) {89 return response.data;90 });91 }92 // delete a service. will only work for the dashboard that created it93 function deleteService(dashboardId, serviceId) {94 return $http.delete(HygieiaConfig.local ? testingDetailRoute : getServiceRoute(dashboardId) + serviceId)95 .then(function (response) {96 return response.data;97 });98 }99 // add a new dependent service on the dashboard100 function createDependentService(dashboardId, serviceId) {101 return $http.post(HygieiaConfig.local ? testingDetailRoute : getDependentServiceRoute(dashboardId) + serviceId, {})102 .then(function (response) {103 return response.data;104 });105 }106 // delete an existing dependent service107 function deleteDependentService(dashboardId, serviceId) {108 return $http.delete(HygieiaConfig.local ? testingDetailRoute : getDependentServiceRoute(dashboardId) + serviceId)109 .then(function (response) {110 return response.data;111 });112 }113 }...
mock-data.module.ts
Source:mock-data.module.ts
1import { NgModule, ModuleWithProviders } from '@angular/core';2import { CommonModule } from '@angular/common';3import { UserService } from './users.service';4import { ElectricityService } from './electricity.service';5import { SmartTableService } from './smart-table.service';6import { UserActivityService } from './user-activity.service';7import { OrdersChartService } from './orders-chart.service';8import { ProfitChartService } from './profit-chart.service';9import { TrafficListService } from './traffic-list.service';10import { PeriodsService } from './periods.service';11import { EarningService } from './earning.service';12import { OrdersProfitChartService } from './orders-profit-chart.service';13import { TrafficBarService } from './traffic-bar.service';14import { ProfitBarAnimationChartService } from './profit-bar-animation-chart.service';15import { TemperatureHumidityService } from './temperature-humidity.service';16import { SolarService } from './solar.service';17import { TrafficChartService } from './traffic-chart.service';18import { StatsBarService } from './stats-bar.service';19import { CountryOrderService } from './country-order.service';20import { StatsProgressBarService } from './stats-progress-bar.service';21import { VisitorsAnalyticsService } from './visitors-analytics.service';22import { SecurityCamerasService } from './security-cameras.service';23const SERVICES = [24 UserService,25 ElectricityService,26 SmartTableService,27 UserActivityService,28 OrdersChartService,29 ProfitChartService,30 TrafficListService,31 PeriodsService,32 EarningService,33 OrdersProfitChartService,34 TrafficBarService,35 ProfitBarAnimationChartService,36 TemperatureHumidityService,37 SolarService,38 TrafficChartService,39 StatsBarService,40 CountryOrderService,41 StatsProgressBarService,42 VisitorsAnalyticsService,43 SecurityCamerasService,44];45@NgModule({46 imports: [47 CommonModule,48 ],49 providers: [50 ...SERVICES,51 ],52})53export class MockDataModule {54 static forRoot(): ModuleWithProviders<MockDataModule> {55 return {56 ngModule: MockDataModule,57 providers: [58 ...SERVICES,59 ],60 };61 }...
Using AI Code Generation
1import { TestBed } from '@angular/core/testing';2import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';3import { AppComponent } from './app.component';4import { AppService } from './app.service';5describe('AppComponent', () => {6 beforeEach(() => MockBuilder(AppComponent).mock(AppService));7 it('should create the app', () => {8 const fixture = MockRender(AppComponent);9 const app = fixture.point.componentInstance;10 expect(app).toBeTruthy();11 });12 it(`should have as title 'ng-mocks'`, () => {13 const fixture = MockRender(AppComponent);14 const app = fixture.point.componentInstance;15 expect(app.title).toEqual('ng-mocks');16 });17 it('should render title in a h1 tag', () => {18 const fixture = MockRender(AppComponent);19 fixture.detectChanges();20 const compiled = fixture.point.nativeElement;21 expect(compiled.querySelector('h1').textContent).toContain(22 );23 });24 it('should use service', () => {25 const fixture = MockRender(AppComponent);26 const appService = ngMocks.findInstance(AppService);27 const spy = spyOn(appService, 'getValue').and.returnValue('bar');28 fixture.detectChanges();29 const compiled = fixture.point.nativeElement;30 expect(compiled.querySelector('h1').textContent).toContain('bar');31 expect(spy).toHaveBeenCalled();32 });33});
Using AI Code Generation
1import { MockBuilder, MockInstance, MockRender } from 'ng-mocks';2import { AppComponent } from './app.component';3import { MyService } from './my.service';4describe('AppComponent', () => {5 beforeEach(() => MockBuilder(AppComponent, MyService));6 it('should create the app', () => {7 const fixture = MockRender(AppComponent);8 const app = fixture.point.componentInstance;9 expect(app).toBeTruthy();10 });11 it('should use the value from the real service', () => {12 MockInstance(MyService, 'value', 'real value');13 const fixture = MockRender(AppComponent);14 const app = fixture.point.componentInstance;15 expect(app.value).toEqual('real value');16 });17 it('should use the fake value from the mock', () => {18 const fixture = MockRender(AppComponent);19 const app = fixture.point.componentInstance;20 expect(app.value).toEqual('faked value');21 });22});
Using AI Code Generation
1import { MockBuilder, MockRender, MockInstance } from 'ng-mocks';2import { AppComponent } from './app.component';3import { AppModule } from './app.module';4import { HttpClient } from '@angular/common/http';5import { of } from 'rxjs';6describe('AppComponent', () => {7 beforeEach(() => MockBuilder(AppComponent, AppModule));8 it('should create the app', () => {9 MockInstance(HttpClient, {10 get: () => of({}),11 });12 const fixture = MockRender(AppComponent);13 const app = fixture.point.componentInstance;14 expect(app).toBeTruthy();15 });16});
Using AI Code Generation
1var mock = ngMocks.default;2var mock = ngMocks.default;3import { mock } from 'ng-mocks';4import { mock } from 'ng-mocks';5import { service } from 'ng-mocks';6import { service } from 'ng-mocks';7import { helper } from 'ng-mocks';8import { helper } from 'ng-mocks';9import { render } from 'ng-mocks';10import { render } from 'ng-mocks';11import { find } from 'ng-mocks';12import { find } from 'ng-mocks';13import { findInstance } from 'ng-mocks';14import { findInstance } from 'ng-mocks';15import { findComponent } from 'ng-mocks';16import { findComponent } from 'ng-mocks';17import { findDirective } from 'ng-mocks';18import { findDirective } from 'ng-mocks';19import { findPipe } from 'ng-mocks';20import { findPipe } from 'ng-mocks';21import { findDebugElement } from 'ng-mocks';
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!