add unit test

This commit is contained in:
Daniel Rodriguez 2022-08-27 23:06:09 +02:00
parent 275bd37552
commit 02932ee64b
21 changed files with 19754 additions and 19754 deletions

View file

@ -1,112 +1,112 @@
{ {
"$schema": "./node_modules/@angular/cli/lib/config/schema.json", "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1, "version": 1,
"newProjectRoot": "projects", "newProjectRoot": "projects",
"projects": { "projects": {
"TFTPaths": { "TFTPaths": {
"projectType": "application", "projectType": "application",
"schematics": { "schematics": {
"@schematics/angular:component": { "@schematics/angular:component": {
"style": "scss" "style": "scss"
} }
}, },
"root": "", "root": "",
"sourceRoot": "src", "sourceRoot": "src",
"prefix": "app", "prefix": "app",
"architect": { "architect": {
"build": { "build": {
"builder": "@angular-devkit/build-angular:browser", "builder": "@angular-devkit/build-angular:browser",
"options": { "options": {
"outputPath": "dist/TFTPaths", "outputPath": "dist/TFTPaths",
"index": "src/index.html", "index": "src/index.html",
"main": "src/main.ts", "main": "src/main.ts",
"polyfills": "src/polyfills.ts", "polyfills": "src/polyfills.ts",
"tsConfig": "tsconfig.app.json", "tsConfig": "tsconfig.app.json",
"aot": false, "aot": false,
"assets": [ "assets": [
"src/favicon.ico", "src/favicon.ico",
"src/assets" "src/assets"
], ],
"styles": [ "styles": [
"src/styles.scss" "src/styles.scss"
], ],
"scripts": [] "scripts": []
}, },
"configurations": { "configurations": {
"production": { "production": {
"fileReplacements": [ "fileReplacements": [
{ {
"replace": "src/environments/environment.ts", "replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts" "with": "src/environments/environment.prod.ts"
} }
], ],
"optimization": true, "optimization": true,
"outputHashing": "all", "outputHashing": "all",
"sourceMap": false, "sourceMap": false,
"extractCss": true, "extractCss": true,
"namedChunks": false, "namedChunks": false,
"aot": true, "aot": true,
"extractLicenses": true, "extractLicenses": true,
"vendorChunk": false, "vendorChunk": false,
"buildOptimizer": true, "buildOptimizer": true,
"budgets": [ "budgets": [
{ {
"type": "initial", "type": "initial",
"maximumWarning": "2mb", "maximumWarning": "2mb",
"maximumError": "5mb" "maximumError": "5mb"
}, },
{ {
"type": "anyComponentStyle", "type": "anyComponentStyle",
"maximumWarning": "6kb", "maximumWarning": "6kb",
"maximumError": "10kb" "maximumError": "10kb"
} }
] ]
} }
} }
}, },
"serve": { "serve": {
"builder": "@angular-devkit/build-angular:dev-server", "builder": "@angular-devkit/build-angular:dev-server",
"options": { "options": {
"browserTarget": "TFTPaths:build" "browserTarget": "TFTPaths:build"
}, },
"configurations": { "configurations": {
"production": { "production": {
"browserTarget": "TFTPaths:build:production" "browserTarget": "TFTPaths:build:production"
} }
} }
}, },
"extract-i18n": { "extract-i18n": {
"builder": "@angular-devkit/build-angular:extract-i18n", "builder": "@angular-devkit/build-angular:extract-i18n",
"options": { "options": {
"browserTarget": "TFTPaths:build" "browserTarget": "TFTPaths:build"
} }
}, },
"lint": { "lint": {
"builder": "@angular-devkit/build-angular:tslint", "builder": "@angular-devkit/build-angular:tslint",
"options": { "options": {
"tsConfig": [ "tsConfig": [
"tsconfig.app.json", "tsconfig.app.json",
"tsconfig.spec.json", "tsconfig.spec.json",
"e2e/tsconfig.json" "e2e/tsconfig.json"
], ],
"exclude": [ "exclude": [
"**/node_modules/**" "**/node_modules/**"
] ]
} }
}, },
"e2e": { "e2e": {
"builder": "@angular-devkit/build-angular:protractor", "builder": "@angular-devkit/build-angular:protractor",
"options": { "options": {
"protractorConfig": "e2e/protractor.conf.js", "protractorConfig": "e2e/protractor.conf.js",
"devServerTarget": "TFTPaths:serve" "devServerTarget": "TFTPaths:serve"
}, },
"configurations": { "configurations": {
"production": { "production": {
"devServerTarget": "TFTPaths:serve:production" "devServerTarget": "TFTPaths:serve:production"
} }
} }
} }
} }
}}, }},
"defaultProject": "TFTPaths" "defaultProject": "TFTPaths"
} }

View file

@ -1,15 +1,15 @@
const { pathsToModuleNameMapper } = require('ts-jest/utils'); const { pathsToModuleNameMapper } = require('ts-jest/utils');
const { compilerOptions } = require('./tsconfig'); const { compilerOptions } = require('./tsconfig');
module.exports = { module.exports = {
preset: 'jest-preset-angular', preset: 'jest-preset-angular',
roots: ['<rootDir>/src/'], roots: ['<rootDir>/src/'],
testMatch: ['**/+(*.)+(spec).+(ts)'], testMatch: ['**/+(*.)+(spec).+(ts)'],
setupFilesAfterEnv: ['<rootDir>/src/test.ts'], setupFilesAfterEnv: ['<rootDir>/src/test.ts'],
collectCoverage: true, collectCoverage: true,
coverageReporters: ['html'], coverageReporters: ['html'],
coverageDirectory: 'coverage/my-app', coverageDirectory: 'coverage/my-app',
moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths || {}, { moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths || {}, {
prefix: '<rootDir>/' prefix: '<rootDir>/'
}) })
}; };

35470
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -1,46 +1,46 @@
{ {
"name": "tftpaths", "name": "tftpaths",
"version": "0.0.0", "version": "0.0.0",
"scripts": { "scripts": {
"ng": "ng", "ng": "ng",
"start": "ng serve", "start": "ng serve",
"build": "ng build", "build": "ng build",
"test": "npx jest", "test": "npx jest",
"lint": "ng lint", "lint": "ng lint",
"e2e": "ng e2e" "e2e": "ng e2e"
}, },
"private": true, "private": true,
"dependencies": { "dependencies": {
"@angular/animations": "^11.2.11", "@angular/animations": "^11.2.11",
"@angular/common": "^11.2.11", "@angular/common": "^11.2.11",
"@angular/compiler": "^11.2.11", "@angular/compiler": "^11.2.11",
"@angular/core": "^11.2.11", "@angular/core": "^11.2.11",
"@angular/forms": "^11.2.11", "@angular/forms": "^11.2.11",
"@angular/platform-browser": "^11.2.11", "@angular/platform-browser": "^11.2.11",
"@angular/platform-browser-dynamic": "^11.2.11", "@angular/platform-browser-dynamic": "^11.2.11",
"@angular/router": "^11.2.11", "@angular/router": "^11.2.11",
"lodash": "^4.17.21", "lodash": "^4.17.21",
"rxjs": "~6.6.7", "rxjs": "~6.6.7",
"tslib": "^1.14.1", "tslib": "^1.14.1",
"zone.js": "~0.10.3" "zone.js": "~0.10.3"
}, },
"devDependencies": { "devDependencies": {
"@angular-devkit/build-angular": "^0.1102.10", "@angular-devkit/build-angular": "^0.1102.10",
"@angular/cli": "^11.2.10", "@angular/cli": "^11.2.10",
"@angular/compiler-cli": "^11.2.11", "@angular/compiler-cli": "^11.2.11",
"@angular/language-service": "^11.2.11", "@angular/language-service": "^11.2.11",
"@types/jasmine": "~3.3.8", "@types/jasmine": "~3.3.8",
"@types/jasminewd2": "^2.0.8", "@types/jasminewd2": "^2.0.8",
"@types/jest": "^27.0.2", "@types/jest": "^27.0.2",
"@types/node": "~8.9.4", "@types/node": "~8.9.4",
"codelyzer": "^6.0.1", "codelyzer": "^6.0.1",
"jasmine-core": "~3.4.0", "jasmine-core": "~3.4.0",
"jasmine-spec-reporter": "~4.2.1", "jasmine-spec-reporter": "~4.2.1",
"jest": "^27.3.1", "jest": "^27.3.1",
"jest-preset-angular": "^10.0.1", "jest-preset-angular": "^10.0.1",
"protractor": "^7.0.0", "protractor": "^7.0.0",
"ts-node": "~7.0.0", "ts-node": "~7.0.0",
"tslint": "~6.1.3", "tslint": "~6.1.3",
"typescript": "~4.0.7" "typescript": "~4.0.7"
} }
} }

View file

@ -1,30 +1,30 @@
import { TestBed, waitForAsync } from '@angular/core/testing'; import { TestBed, waitForAsync } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing'; import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component'; import { AppComponent } from './app.component';
describe('AppComponent', () => { describe('AppComponent', () => {
beforeEach(waitForAsync(() => { beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [
RouterTestingModule RouterTestingModule
], ],
declarations: [ declarations: [
AppComponent AppComponent
], ],
}).compileComponents(); }).compileComponents();
})); }));
it('should create the app', () => { it('should create the app', () => {
const fixture = TestBed.createComponent(AppComponent); const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance; const app = fixture.debugElement.componentInstance;
expect(app).toBeTruthy(); expect(app).toBeTruthy();
}); });
it(`should have as title 'TFTPaths'`, () => { it(`should have as title 'TFTPaths'`, () => {
const fixture = TestBed.createComponent(AppComponent); const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance; const app = fixture.debugElement.componentInstance;
app.ngOnInit(); app.ngOnInit();
expect(app.title).toEqual('TFTPaths'); expect(app.title).toEqual('TFTPaths');
}); });
}); });

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,18 +1,18 @@
import { Bonus } from './bonus'; import { Bonus } from './bonus';
describe('Bonus', () => { describe('Bonus', () => {
let bonus: Bonus; let bonus: Bonus;
beforeEach(() => { beforeEach(() => {
bonus = new Bonus('bonus example', 'knight', 1, 6); bonus = new Bonus('bonus example', 'knight', 1, 6);
}); });
it('should create a bonus', () => { it('should create a bonus', () => {
const mockBonus = { const mockBonus = {
description: 'bonus example', description: 'bonus example',
role: 'knight', role: 'knight',
units: 1, units: 1,
maxUnits: 6 maxUnits: 6
} }
expect(bonus).toEqual(mockBonus); expect(bonus).toEqual(mockBonus);
}); });
}); });

View file

@ -1,21 +1,21 @@
import { Champion } from './champion'; import { Champion } from './champion';
describe('Champion', () => { describe('Champion', () => {
let champion: Champion; let champion: Champion;
beforeEach(() => { beforeEach(() => {
champion = new Champion('John Doe', 'johndoe', ['knight'], 3, false, false, false); champion = new Champion('John Doe', 'johndoe', ['knight'], 3, false, false, false);
}); });
it('should create a bonus', () => { it('should create a bonus', () => {
const mockChampion = { const mockChampion = {
name: 'John Doe', name: 'John Doe',
img: 'johndoe', img: 'johndoe',
roles: ['knight'], roles: ['knight'],
cost: 3, cost: 3,
isSelected: false, isSelected: false,
sinergy: false, sinergy: false,
sinergy2: false sinergy2: false
} }
expect(champion).toEqual(mockChampion); expect(champion).toEqual(mockChampion);
}); });
}); });

View file

@ -1,25 +1,25 @@
import { Bonus } from './bonus'; import { Bonus } from './bonus';
import { Champion } from './champion'; import { Champion } from './champion';
import { DataToShare } from './dataToShare'; import { DataToShare } from './dataToShare';
describe('DataToShare', () => { describe('DataToShare', () => {
let dataToShare: DataToShare; let dataToShare: DataToShare;
const champion = new Champion('John Doe', 'johndoe', ['knight'], 3, false, false, false); const champion = new Champion('John Doe', 'johndoe', ['knight'], 3, false, false, false);
const bonus = new Bonus('bonus example', 'knight', 1, 6); const bonus = new Bonus('bonus example', 'knight', 1, 6);
beforeEach(() => { beforeEach(() => {
dataToShare = new DataToShare([champion], ['knight'], [3, 6], ['knight'], [bonus], true, 1); dataToShare = new DataToShare([champion], ['knight'], [3, 6], ['knight'], [bonus], true, 1);
}); });
it('should create a bonus', () => { it('should create a bonus', () => {
const mockDataToShare = { const mockDataToShare = {
champions: [champion], champions: [champion],
roles: ['knight'], roles: ['knight'],
rolesCount: [3, 6], rolesCount: [3, 6],
rolesPool: ['knight'], rolesPool: ['knight'],
bonusesPool: [bonus], bonusesPool: [bonus],
noChampSelected: true, noChampSelected: true,
teamSize: 1 teamSize: 1
} }
expect(dataToShare).toEqual(mockDataToShare); expect(dataToShare).toEqual(mockDataToShare);
}); });
}); });

View file

@ -1,40 +1,40 @@
import { TestBed, waitForAsync } from '@angular/core/testing'; import { TestBed, waitForAsync } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing'; import { RouterTestingModule } from '@angular/router/testing';
import { CardComponent } from './card.component'; import { CardComponent } from './card.component';
describe('CardComponent', () => { describe('CardComponent', () => {
beforeEach(waitForAsync(() => { beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [
RouterTestingModule RouterTestingModule
], ],
declarations: [ declarations: [
CardComponent CardComponent
], ],
}).compileComponents(); }).compileComponents();
})); }));
it('should create a card', () => { it('should create a card', () => {
const fixture = TestBed.createComponent(CardComponent); const fixture = TestBed.createComponent(CardComponent);
const card = fixture.debugElement.componentInstance; const card = fixture.debugElement.componentInstance;
expect(card).toBeTruthy(); expect(card).toBeTruthy();
}); });
it('should get a imageUrl', () => { it('should get a imageUrl', () => {
const mockResponse = 'url(../../assets/images/champions/johndoe.png)'; const mockResponse = 'url(../../assets/images/champions/johndoe.png)';
const fixture = TestBed.createComponent(CardComponent); const fixture = TestBed.createComponent(CardComponent);
const card = fixture.debugElement.componentInstance; const card = fixture.debugElement.componentInstance;
expect(card.getImage('johndoe').changingThisBreaksApplicationSecurity).toEqual(mockResponse); expect(card.getImage('johndoe').changingThisBreaksApplicationSecurity).toEqual(mockResponse);
}); });
it('should emit a value', () => { it('should emit a value', () => {
const fixture = TestBed.createComponent(CardComponent); const fixture = TestBed.createComponent(CardComponent);
const card = fixture.debugElement.componentInstance; const card = fixture.debugElement.componentInstance;
let valueEmitted; let valueEmitted;
card.championClicked.subscribe( event =>{ card.championClicked.subscribe( event =>{
valueEmitted = event; valueEmitted = event;
}) })
card.selectChampion('John Doe'); card.selectChampion('John Doe');
expect(valueEmitted).toBe('John Doe'); expect(valueEmitted).toBe('John Doe');
}); });
}); });

View file

@ -1,41 +1,41 @@
import { Component, EventEmitter, Input, Output} from '@angular/core'; import { Component, EventEmitter, Input, Output} from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser'; import { DomSanitizer } from '@angular/platform-browser';
import { Champion } from '@models/champion'; import { Champion } from '@models/champion';
@Component({ @Component({
selector: 'app-card', selector: 'app-card',
templateUrl: './card.component.html', templateUrl: './card.component.html',
styleUrls: ['./card.component.scss'] styleUrls: ['./card.component.scss']
}) })
export class CardComponent{ export class CardComponent{
@Input() champion: Champion; @Input() champion: Champion;
@Input() noChampSelected: boolean; @Input() noChampSelected: boolean;
@Output() championClicked = new EventEmitter<Champion>(); @Output() championClicked = new EventEmitter<Champion>();
constructor( constructor(
private sanitizer: DomSanitizer, private sanitizer: DomSanitizer,
) {} ) {}
/** /**
* Get champion image * Get champion image
* @param name Champion name * @param name Champion name
*/ */
getImage(name) { getImage(name) {
return this.sanitizer.bypassSecurityTrustStyle(`url(${'../../assets/images/champions/' + name + '.png'})`); return this.sanitizer.bypassSecurityTrustStyle(`url(${'../../assets/images/champions/' + name + '.png'})`);
} }
/** /**
* Send output to parent with champion clicked * Send output to parent with champion clicked
* @param champion Champion * @param champion Champion
*/ */
selectChampion(champion) { selectChampion(champion) {
this.championClicked.emit(champion); this.championClicked.emit(champion);
} }
} }

View file

@ -1,73 +1,73 @@
import { TestBed, waitForAsync } from '@angular/core/testing'; import { TestBed, waitForAsync } from '@angular/core/testing';
import { ReactiveFormsModule } from '@angular/forms'; import { ReactiveFormsModule } from '@angular/forms';
import { RouterTestingModule } from '@angular/router/testing'; import { RouterTestingModule } from '@angular/router/testing';
import { CardComponent } from '../card/card.component'; import { CardComponent } from '../card/card.component';
import { PoolComponent } from './pool.component'; import { PoolComponent } from './pool.component';
describe('PoolComponent', () => { describe('PoolComponent', () => {
beforeEach(waitForAsync(() => { beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [
RouterTestingModule, RouterTestingModule,
ReactiveFormsModule ReactiveFormsModule
], ],
declarations: [ declarations: [
PoolComponent, PoolComponent,
CardComponent CardComponent
], ],
}).compileComponents(); }).compileComponents();
})); }));
it('should create a pool', () => { it('should create a pool', () => {
const fixture = TestBed.createComponent(PoolComponent); const fixture = TestBed.createComponent(PoolComponent);
const pool = fixture.debugElement.componentInstance; const pool = fixture.debugElement.componentInstance;
expect(pool).toBeTruthy(); expect(pool).toBeTruthy();
}); });
it('should set form teamSize', () => { it('should set form teamSize', () => {
const fixture = TestBed.createComponent(PoolComponent); const fixture = TestBed.createComponent(PoolComponent);
const pool = fixture.debugElement.componentInstance; const pool = fixture.debugElement.componentInstance;
pool.ngOnInit(); pool.ngOnInit();
expect(pool.formFilters).toBeTruthy(); expect(pool.formFilters).toBeTruthy();
}); });
it('should select a Champion', () => { it('should select a Champion', () => {
const fixture = TestBed.createComponent(PoolComponent); const fixture = TestBed.createComponent(PoolComponent);
const pool = fixture.debugElement.componentInstance; const pool = fixture.debugElement.componentInstance;
const mockChampion = pool.champions[0]; const mockChampion = pool.champions[0];
pool.ngOnInit(); pool.ngOnInit();
pool.selectChampion(mockChampion); pool.selectChampion(mockChampion);
expect(pool.teamSize).toBe(1); expect(pool.teamSize).toBe(1);
expect(pool.rolesPool).toContain(mockChampion.roles[0]); expect(pool.rolesPool).toContain(mockChampion.roles[0]);
}); });
it('should select a Role', () => { it('should select a Role', () => {
const fixture = TestBed.createComponent(PoolComponent); const fixture = TestBed.createComponent(PoolComponent);
const pool = fixture.debugElement.componentInstance; const pool = fixture.debugElement.componentInstance;
const mockRole = pool.champions[0].roles[0]; const mockRole = pool.champions[0].roles[0];
pool.ngOnInit(); pool.ngOnInit();
pool.selectRole(mockRole); pool.selectRole(mockRole);
expect(pool.teamSize).toBeGreaterThan(0); expect(pool.teamSize).toBeGreaterThan(0);
}); });
it('should check if a role is selected', () => { it('should check if a role is selected', () => {
const fixture = TestBed.createComponent(PoolComponent); const fixture = TestBed.createComponent(PoolComponent);
const pool = fixture.debugElement.componentInstance; const pool = fixture.debugElement.componentInstance;
const mockRole = pool.champions[0].roles[0]; const mockRole = pool.champions[0].roles[0];
pool.ngOnInit(); pool.ngOnInit();
pool.selectRole(mockRole); pool.selectRole(mockRole);
expect(pool.checkRoleFilter(mockRole)).toBe(true); expect(pool.checkRoleFilter(mockRole)).toBe(true);
}); });
it('should reset composition', () => { it('should reset composition', () => {
const fixture = TestBed.createComponent(PoolComponent); const fixture = TestBed.createComponent(PoolComponent);
const pool = fixture.debugElement.componentInstance; const pool = fixture.debugElement.componentInstance;
const mockRole = pool.champions[0].roles[0]; const mockRole = pool.champions[0].roles[0];
pool.ngOnInit(); pool.ngOnInit();
pool.selectRole(mockRole); pool.selectRole(mockRole);
pool.resetComposition(); pool.resetComposition();
expect(pool.teamSize).toBe(0); expect(pool.teamSize).toBe(0);
expect(pool.rolesCount.lenght).toBeUndefined(); expect(pool.rolesCount.lenght).toBeUndefined();
expect(pool.rolesPool.lenght).toBeUndefined(); expect(pool.rolesPool.lenght).toBeUndefined();
}); });
}); });

View file

@ -1,100 +1,100 @@
import { Component, OnDestroy, OnInit } from '@angular/core'; import { Component, OnDestroy, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms'; import { FormBuilder, FormGroup } from '@angular/forms';
import { Champion } from '@models/champion'; import { Champion } from '@models/champion';
import { Bonus } from '@models/bonus'; import { Bonus } from '@models/bonus';
import { PoolService } from '@modules/pool/services/pool.service'; import { PoolService } from '@modules/pool/services/pool.service';
import * as _ from 'lodash'; import * as _ from 'lodash';
import { Subscription } from 'rxjs'; import { Subscription } from 'rxjs';
import { DataToShare } from '@models/dataToShare'; import { DataToShare } from '@models/dataToShare';
@Component({ @Component({
selector: 'app-pool', selector: 'app-pool',
templateUrl: './pool.component.html', templateUrl: './pool.component.html',
styleUrls: ['./pool.component.scss'] styleUrls: ['./pool.component.scss']
}) })
export class PoolComponent implements OnInit, OnDestroy { export class PoolComponent implements OnInit, OnDestroy {
formFilters: FormGroup; formFilters: FormGroup;
bonusesPool: Bonus[] = []; bonusesPool: Bonus[] = [];
champions: Champion[] = []; champions: Champion[] = [];
noChampSelected = true; noChampSelected = true;
roles: string[] = []; roles: string[] = [];
rolesCount: number[] = []; rolesCount: number[] = [];
rolesPool: string[] = []; rolesPool: string[] = [];
teamSize = 0; teamSize = 0;
subscription: Subscription; subscription: Subscription;
constructor( constructor(
private fb: FormBuilder, private fb: FormBuilder,
private poolService: PoolService private poolService: PoolService
) { ) {
this.subscription = this.poolService.setChampions().subscribe( (data: DataToShare) => { this.subscription = this.poolService.setChampions().subscribe( (data: DataToShare) => {
if (data) { if (data) {
const {champions, roles, rolesPool, bonusesPool, noChampSelected, teamSize} = data; const {champions, roles, rolesPool, bonusesPool, noChampSelected, teamSize} = data;
this.champions = champions; this.champions = champions;
this.roles = roles; this.roles = roles;
this.rolesPool = rolesPool; this.rolesPool = rolesPool;
this.bonusesPool = bonusesPool; this.bonusesPool = bonusesPool;
this.noChampSelected = noChampSelected; this.noChampSelected = noChampSelected;
this.teamSize = teamSize; this.teamSize = teamSize;
} }
}) })
} }
ngOnInit(): void { ngOnInit(): void {
this.formFilters = this.fb.group({ this.formFilters = this.fb.group({
teamSize: [this.teamSize] teamSize: [this.teamSize]
}); });
} }
ngOnDestroy(): void { ngOnDestroy(): void {
if(this.subscription) { if(this.subscription) {
this.subscription.unsubscribe(); this.subscription.unsubscribe();
} }
} }
/** /**
* Select or unselect champion * Select or unselect champion
* @param champion model * @param champion model
*/ */
selectChampion(champion) { selectChampion(champion) {
this.poolService.selectChampion(champion); this.poolService.selectChampion(champion);
this.formFilters.patchValue({ this.formFilters.patchValue({
teamSize: this.teamSize teamSize: this.teamSize
}); });
} }
/** /**
* Select role pool * Select role pool
* @param role name of role * @param role name of role
*/ */
selectRole(role) { selectRole(role) {
this.poolService.selectRole(role); this.poolService.selectRole(role);
this.formFilters.patchValue({ this.formFilters.patchValue({
teamSize: this.teamSize teamSize: this.teamSize
}); });
} }
/** /**
* Check role filter selected * Check role filter selected
* @param role name * @param role name
*/ */
checkRoleFilter(role) { checkRoleFilter(role) {
return this.poolService.checkRoleFilter(role); return this.poolService.checkRoleFilter(role);
} }
/** /**
* Reset composition * Reset composition
*/ */
resetComposition() { resetComposition() {
this.poolService.resetComposition(); this.poolService.resetComposition();
this.formFilters.patchValue({ this.formFilters.patchValue({
teamSize: this.teamSize teamSize: this.teamSize
}); });
} }
} }

View file

@ -1,25 +1,25 @@
import { NgModule } from '@angular/core'; import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common'; import { CommonModule } from '@angular/common';
import { PoolRoutingModule } from './pool-routing.module'; import { PoolRoutingModule } from './pool-routing.module';
import { ReactiveFormsModule } from '@angular/forms'; import { ReactiveFormsModule } from '@angular/forms';
import { PoolService } from '@modules/pool/services/pool.service'; import { PoolService } from '@modules/pool/services/pool.service';
import { PoolComponent } from './components/pool/pool.component'; import { PoolComponent } from './components/pool/pool.component';
import { CardComponent } from './components/card/card.component'; import { CardComponent } from './components/card/card.component';
@NgModule({ @NgModule({
declarations: [ declarations: [
PoolComponent, PoolComponent,
CardComponent CardComponent
], ],
imports: [ imports: [
CommonModule, CommonModule,
PoolRoutingModule, PoolRoutingModule,
ReactiveFormsModule ReactiveFormsModule
], ],
providers: [PoolService] providers: [PoolService]
}) })
export class PoolModule { } export class PoolModule { }

View file

@ -1,66 +1,66 @@
import { PoolService } from './pool.service'; import { PoolService } from './pool.service';
describe('PoolService', () => { describe('PoolService', () => {
let poolService: PoolService; let poolService: PoolService;
beforeEach(() => { beforeEach(() => {
poolService = new PoolService(); poolService = new PoolService();
}); });
it('should set Champions', () => { it('should set Champions', () => {
let dataSet; let dataSet;
poolService.dataToShare.subscribe( data => { poolService.dataToShare.subscribe( data => {
dataSet = data; dataSet = data;
}) })
poolService.setChampions(); poolService.setChampions();
expect(dataSet).not.toBeNull(); expect(dataSet).not.toBeNull();
}); });
it('should update data to share', () => { it('should update data to share', () => {
let dataSetBefore; let dataSetBefore;
let dataSetAfter; let dataSetAfter;
poolService.dataToShare.subscribe( data => { poolService.dataToShare.subscribe( data => {
if (dataSetBefore === undefined) { if (dataSetBefore === undefined) {
dataSetBefore = data; dataSetBefore = data;
} else { } else {
dataSetAfter = data; dataSetAfter = data;
} }
}); });
poolService.setChampions(); poolService.setChampions();
poolService.updateDataToShare(); poolService.updateDataToShare();
expect(dataSetBefore).not.toEqual(dataSetAfter); expect(dataSetBefore).not.toEqual(dataSetAfter);
}); });
it('should select a champion', () => { it('should select a champion', () => {
const mockChampion = poolService.champions[0]; const mockChampion = poolService.champions[0];
poolService.setChampions(); poolService.setChampions();
poolService.selectChampion(mockChampion); poolService.selectChampion(mockChampion);
expect(poolService.teamSize).toBe(1); expect(poolService.teamSize).toBe(1);
poolService.selectChampion(mockChampion); poolService.selectChampion(mockChampion);
expect(poolService.teamSize).toBe(0); expect(poolService.teamSize).toBe(0);
}); });
it('should select a role', () => { it('should select a role', () => {
const mockRole = poolService.champions[0].roles[0]; const mockRole = poolService.champions[0].roles[0];
poolService.setChampions(); poolService.setChampions();
poolService.selectRole(mockRole); poolService.selectRole(mockRole);
expect(poolService.teamSize).toBeGreaterThan(0); expect(poolService.teamSize).toBeGreaterThan(0);
poolService.selectRole(mockRole); poolService.selectRole(mockRole);
expect(poolService.teamSize).toBe(0); expect(poolService.teamSize).toBe(0);
}); });
it('should check role filter', () => { it('should check role filter', () => {
const mockRole = poolService.champions[0].roles[0]; const mockRole = poolService.champions[0].roles[0];
poolService.setChampions(); poolService.setChampions();
poolService.selectRole(mockRole); poolService.selectRole(mockRole);
expect(poolService.checkRoleFilter(mockRole)).toBe(true); expect(poolService.checkRoleFilter(mockRole)).toBe(true);
poolService.selectRole(mockRole); poolService.selectRole(mockRole);
expect(poolService.checkRoleFilter(mockRole)).toBe(false); expect(poolService.checkRoleFilter(mockRole)).toBe(false);
}); });
it('should sort champions', () => { it('should sort champions', () => {
poolService.setChampions(); poolService.setChampions();
poolService.championSort('cost'); poolService.championSort('cost');
expect(poolService.champions[0].cost).toBe(1); expect(poolService.champions[0].cost).toBe(1);
}); });
}); });

View file

@ -1,214 +1,214 @@
import { Injectable } from '@angular/core'; import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs'; import { BehaviorSubject, Observable } from 'rxjs';
import { Constants } from '@shared/constants'; import { Constants } from '@shared/constants';
import { Bonus } from '@models/bonus'; import { Bonus } from '@models/bonus';
import { Champion } from '@models/champion'; import { Champion } from '@models/champion';
import { DataToShare } from '@models/dataToShare'; import { DataToShare } from '@models/dataToShare';
import * as _ from 'lodash'; import * as _ from 'lodash';
@Injectable({ @Injectable({
providedIn: 'root', providedIn: 'root',
}) })
export class PoolService { export class PoolService {
bonuses: Bonus[] = [...Constants.bonuses]; bonuses: Bonus[] = [...Constants.bonuses];
bonusesPool: Bonus[] = []; bonusesPool: Bonus[] = [];
champions: Champion[] = [...Constants.Champions]; champions: Champion[] = [...Constants.Champions];
championsPool: Champion[] = []; championsPool: Champion[] = [];
noChampSelected = true; noChampSelected = true;
roles: string[]= [...Constants.roles]; roles: string[]= [...Constants.roles];
rolesCount: number[]= []; rolesCount: number[]= [];
rolesPool: string[] = []; rolesPool: string[] = [];
selectedRole = ''; selectedRole = '';
teamSize = 0; teamSize = 0;
dataToShare = new BehaviorSubject<DataToShare>(null); dataToShare = new BehaviorSubject<DataToShare>(null);
constructor() { } constructor() { }
/** /**
* Set Champion pool and return data * Set Champion pool and return data
* @returns Observable * @returns Observable
*/ */
setChampions(): Observable<DataToShare> { setChampions(): Observable<DataToShare> {
this.roles.forEach(role => { this.roles.forEach(role => {
this.rolesCount[role] = 0; this.rolesCount[role] = 0;
}); });
this.championSort(Constants.championName); this.championSort(Constants.championName);
this.updateDataToShare(); this.updateDataToShare();
return this.dataToShare.asObservable(); return this.dataToShare.asObservable();
} }
updateDataToShare(): void { updateDataToShare(): void {
this.dataToShare.next({ this.dataToShare.next({
champions: this.champions, champions: this.champions,
roles: this.roles, roles: this.roles,
rolesCount: this.rolesCount, rolesCount: this.rolesCount,
rolesPool: this.rolesPool, rolesPool: this.rolesPool,
bonusesPool: this.bonusesPool, bonusesPool: this.bonusesPool,
noChampSelected: this.noChampSelected, noChampSelected: this.noChampSelected,
teamSize: this.teamSize teamSize: this.teamSize
}); });
} }
/** /**
* Select or unselect champion * Select or unselect champion
* @param champion model * @param champion model
*/ */
selectChampion(champion) { selectChampion(champion) {
const champIndex = this.champions.findIndex((champ => champ.name === champion.name)); const champIndex = this.champions.findIndex((champ => champ.name === champion.name));
if (!this.champions[champIndex].isSelected) { if (!this.champions[champIndex].isSelected) {
this.champions[champIndex].isSelected = true; this.champions[champIndex].isSelected = true;
this.championsPool.push(champion); this.championsPool.push(champion);
champion.roles.forEach(role => { champion.roles.forEach(role => {
this.rolesCount[role]++; this.rolesCount[role]++;
}); });
this.teamSize++; this.teamSize++;
this.noChampSelected = false; this.noChampSelected = false;
} else { } else {
this.champions[champIndex].isSelected = false; this.champions[champIndex].isSelected = false;
this.championsPool = _.remove(this.championsPool, champ => { this.championsPool = _.remove(this.championsPool, champ => {
return champ.name !== champion.name; return champ.name !== champion.name;
}); });
champion.roles.forEach(role => { champion.roles.forEach(role => {
this.rolesCount[role]--; this.rolesCount[role]--;
}); });
this.teamSize--; this.teamSize--;
if (this.teamSize === 0) { if (this.teamSize === 0) {
this.noChampSelected = true; this.noChampSelected = true;
} }
} }
this.getBonus(); this.getBonus();
this.updatePool(); this.updatePool();
this.updateSinergies(); this.updateSinergies();
this.updateDataToShare(); this.updateDataToShare();
} }
/** /**
* Sort champion by param * Sort champion by param
* @param param use to sort * @param param use to sort
*/ */
championSort(param) { championSort(param) {
this.champions.sort((a, b) => { this.champions.sort((a, b) => {
if (a[param] > b[param]) { if (a[param] > b[param]) {
return 1; return 1;
} }
if (a[param] < b[param]) { if (a[param] < b[param]) {
return -1; return -1;
} }
return 0; return 0;
}); });
} }
/** /**
* Select role pool * Select role pool
* @param role name of role * @param role name of role
*/ */
selectRole(role): void { selectRole(role): void {
if (role !== this.selectedRole) { if (role !== this.selectedRole) {
this.resetComposition(); this.resetComposition();
this.selectedRole = role; this.selectedRole = role;
let countChampions = 0; let countChampions = 0;
this.champions.map(champion => { this.champions.map(champion => {
if (_.indexOf(champion.roles, role) !== -1) { if (_.indexOf(champion.roles, role) !== -1) {
champion.isSelected = true; champion.isSelected = true;
countChampions++; countChampions++;
this.championsPool.push(champion); this.championsPool.push(champion);
champion.roles.forEach(rol => { champion.roles.forEach(rol => {
this.rolesCount[rol]++; this.rolesCount[rol]++;
}); });
} }
return champion; return champion;
}); });
this.updatePool(); this.updatePool();
this.updateSinergies(); this.updateSinergies();
this.teamSize = countChampions; this.teamSize = countChampions;
this.getBonus(); this.getBonus();
this.noChampSelected = false; this.noChampSelected = false;
} else { } else {
this.resetComposition(); this.resetComposition();
} }
this.updateDataToShare(); this.updateDataToShare();
} }
/** /**
* Get champions bonuses * Get champions bonuses
*/ */
getBonus() { getBonus() {
this.bonusesPool = []; this.bonusesPool = [];
this.bonuses.forEach(bonus => { this.bonuses.forEach(bonus => {
if (bonus.units <= this.rolesCount[bonus.role]) { if (bonus.units <= this.rolesCount[bonus.role]) {
this.bonusesPool[bonus.role] = bonus; this.bonusesPool[bonus.role] = bonus;
} }
}); });
} }
/** /**
* Update role pool * Update role pool
*/ */
updatePool() { updatePool() {
this.rolesPool = []; this.rolesPool = [];
this.championsPool.forEach(champion => { this.championsPool.forEach(champion => {
this.rolesPool = _.union(this.rolesPool, champion.roles); this.rolesPool = _.union(this.rolesPool, champion.roles);
}); });
} }
/** /**
* Update sinergies * Update sinergies
*/ */
updateSinergies() { updateSinergies() {
this.champions.map(champion => { this.champions.map(champion => {
champion.sinergy2 = false; champion.sinergy2 = false;
return champion.sinergy = false; return champion.sinergy = false;
}); });
this.champions.map(champion => { this.champions.map(champion => {
let countRoles = 0; let countRoles = 0;
this.rolesPool.forEach(role => { this.rolesPool.forEach(role => {
if (_.indexOf(champion.roles, role) !== -1) { if (_.indexOf(champion.roles, role) !== -1) {
countRoles++; countRoles++;
} }
}); });
switch (countRoles) { switch (countRoles) {
case 1: case 1:
return champion.sinergy = true; return champion.sinergy = true;
case 2: case 2:
return champion.sinergy2 = true; return champion.sinergy2 = true;
} }
}); });
} }
/** /**
* Check role filter selected * Check role filter selected
* @param role name * @param role name
*/ */
checkRoleFilter(role) { checkRoleFilter(role) {
if (this.selectedRole === role) { if (this.selectedRole === role) {
return true; return true;
} else { } else {
return false; return false;
} }
} }
/** /**
* Reset composition * Reset composition
*/ */
resetComposition() { resetComposition() {
this.rolesCount = []; this.rolesCount = [];
this.rolesPool = []; this.rolesPool = [];
this.championsPool = []; this.championsPool = [];
this.noChampSelected = true; this.noChampSelected = true;
this.selectedRole = ''; this.selectedRole = '';
this.teamSize = 0; this.teamSize = 0;
this.champions.map(champion => { this.champions.map(champion => {
champion.sinergy = false; champion.sinergy = false;
champion.sinergy2 = false; champion.sinergy2 = false;
champion.isSelected = false; champion.isSelected = false;
return champion; return champion;
}); });
this.setChampions(); this.setChampions();
this.updateDataToShare(); this.updateDataToShare();
} }
} }

View file

@ -1,35 +1,35 @@
import { Champion } from '@models/champion'; import { Champion } from '@models/champion';
import { Bonus } from '@models/bonus'; import { Bonus } from '@models/bonus';
import champions from '@assets/data/champions.json'; import champions from '@assets/data/champions.json';
import traits from '@assets/data/traits.json'; import traits from '@assets/data/traits.json';
export class Constants { export class Constants {
public static Champions: Champion [] = champions.map(champion => { public static Champions: Champion [] = champions.map(champion => {
const championMapped = new Champion( const championMapped = new Champion(
champion.name, champion.name,
champion.championId, champion.championId,
champion.traits.map(trait => traits.find(t => t.key === trait).name), champion.traits.map(trait => traits.find(t => t.key === trait).name),
champion.cost, champion.cost,
false, false,
false, false,
false false
) )
return championMapped; return championMapped;
}).filter( champion => champion.name !== 'Target Dummy'); }).filter( champion => champion.name !== 'Target Dummy');
public static championName = 'name'; public static championName = 'name';
public static roles = traits.map(trait => trait.name); public static roles = traits.map(trait => trait.name);
public static bonuses: Bonus [] = traits.reduce((previous, current) => { public static bonuses: Bonus [] = traits.reduce((previous, current) => {
current.sets.forEach(set => { current.sets.forEach(set => {
previous.push({ previous.push({
description: current.description, description: current.description,
role: current.name, role: current.name,
units: set.min, units: set.min,
maxUnits: current.sets[current.sets.length-1].min maxUnits: current.sets[current.sets.length-1].min
}) })
}) })
return previous; return previous;
}, []) }, [])
} }

View file

@ -1,23 +1,23 @@
import 'jest-preset-angular/setup-jest'; import 'jest-preset-angular/setup-jest';
Object.defineProperty(window, 'CSS', {value: null}); Object.defineProperty(window, 'CSS', {value: null});
Object.defineProperty(window, 'getComputedStyle', { Object.defineProperty(window, 'getComputedStyle', {
value: () => { value: () => {
return { return {
display: 'none', display: 'none',
appearance: ['-webkit-appearance'] appearance: ['-webkit-appearance']
}; };
} }
}); });
Object.defineProperty(document, 'doctype', { Object.defineProperty(document, 'doctype', {
value: '<!DOCTYPE html>' value: '<!DOCTYPE html>'
}); });
Object.defineProperty(document.body.style, 'transform', { Object.defineProperty(document.body.style, 'transform', {
value: () => { value: () => {
return { return {
enumerable: true, enumerable: true,
configurable: true configurable: true
}; };
} }
}); });

View file

@ -1,32 +1,32 @@
{ {
"compileOnSave": false, "compileOnSave": false,
"compilerOptions": { "compilerOptions": {
"baseUrl": "./", "baseUrl": "./",
"outDir": "./dist/out-tsc", "outDir": "./dist/out-tsc",
"sourceMap": true, "sourceMap": true,
"declaration": false, "declaration": false,
"downlevelIteration": true, "downlevelIteration": true,
"experimentalDecorators": true, "experimentalDecorators": true,
"module": "esnext", "module": "esnext",
"moduleResolution": "node", "moduleResolution": "node",
"importHelpers": true, "importHelpers": true,
"target": "es2015", "target": "es2015",
"typeRoots": [ "typeRoots": [
"node_modules/@types" "node_modules/@types"
], ],
"lib": [ "lib": [
"es2018", "es2018",
"dom" "dom"
], ],
"paths": { "paths": {
"@assets/*": ["src/assets/*"], "@assets/*": ["src/assets/*"],
"@models/*": ["src/models/*"], "@models/*": ["src/models/*"],
"@modules/*": ["src/modules/*"], "@modules/*": ["src/modules/*"],
"@shared/*": ["src/shared/*"] "@shared/*": ["src/shared/*"]
} }
}, },
"angularCompilerOptions": { "angularCompilerOptions": {
"fullTemplateTypeCheck": true, "fullTemplateTypeCheck": true,
"strictInjectionParameters": true "strictInjectionParameters": true
} }
} }

View file

@ -1,21 +1,21 @@
{ {
"extends": "./tsconfig.json", "extends": "./tsconfig.json",
"compilerOptions": { "compilerOptions": {
"outDir": "./out-tsc/spec", "outDir": "./out-tsc/spec",
"types": [ "types": [
"jest", "jest",
"jasmine", "jasmine",
"node" "node"
], ],
"esModuleInterop": true, "esModuleInterop": true,
"emitDecoratorMetadata": true "emitDecoratorMetadata": true
}, },
"files": [ "files": [
"src/test.ts", "src/test.ts",
"src/polyfills.ts" "src/polyfills.ts"
], ],
"include": [ "include": [
"src/**/*.spec.ts", "src/**/*.spec.ts",
"src/**/*.d.ts" "src/**/*.d.ts"
] ]
} }