Skip to content

Commit

Permalink
Merge pull request anihalaney#582 from milansar/BW-756
Browse files Browse the repository at this point in the history
BW-756  Unit test for Recent Games Component and Recent Games Card Component
  • Loading branch information
anihalaney authored May 10, 2020
2 parents 22fc2b0 + 35cd89b commit f90c7de
Show file tree
Hide file tree
Showing 18 changed files with 3,336 additions and 1,377 deletions.
11 changes: 2 additions & 9 deletions angular.json
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,6 @@
"test": {
"builder": "@angular-builders/jest:run",
"options": {
"configPath": "./../../jest.config.js",
"polyfills": "projects/trivia/src/polyfills.ts",
"tsConfig": "/../trivia/tsconfig.spec.json",
"scripts": [],
Expand Down Expand Up @@ -434,10 +433,8 @@
"test": {
"builder": "@angular-builders/jest:run",
"options": {
"configPath": "./../../jest.config.js",
"polyfills": "projects/trivia-admin/src/polyfills.ts",
"tsConfig": "/../trivia-admin/tsconfig.spec.json",
"karmaConfig": "projects/trivia-admin/karma.conf.js",
"styles": [
"projects/trivia-admin/src/styles.css"
],
Expand Down Expand Up @@ -520,10 +517,8 @@
},
"test": {
"builder": "@angular-builders/jest:run",
"options": {
"configPath": "./../../jest.config.js",
"tsConfig":"/../shared-library/tsconfig.spec.json",
"karmaConfig": "projects/shared-library/karma.conf.js"
"options": {
"tsConfig":"/../shared-library/tsconfig.spec.json"
}
},
"lint": {
Expand Down Expand Up @@ -731,10 +726,8 @@
"test": {
"builder": "@angular-builders/jest:run",
"options": {
"configPath": "./../../jest.config.js",
"polyfills": "projects/trivia-editor/src/polyfills.ts",
"tsConfig": "/../trivia-editor/tsconfig.spec.json",
"karmaConfig": "projects/trivia-editor/karma.conf.js",
"styles": [
"projects/trivia-editor/src/styles.css"
],
Expand Down
5 changes: 0 additions & 5 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,6 @@
module.exports = {
collectCoverage: true,
coverageReporters: ['html', 'text-summary'],
coverageDirectory: '<rootDir>/test/coverage',
reporters: ['default', ['jest-stare', {
"resultDir": "test/result",
"coverageLink": "../coverage/index.html"
}]],
moduleNameMapper: {
'^shared-library/(.*)$': '<rootDir>/projects/shared-library/src/lib/$1'
},
Expand Down
8 changes: 8 additions & 0 deletions projects/shared-library/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
module.exports = {
coverageDirectory: '<rootDir>/test/coverage/shared-library',
reporters: ['default', ['jest-stare', {
"resultDir": "test/result/shared-library",
"coverageLink": "./../../coverage/shared-library/index.html"
}]],
};

Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,12 @@ import { provideMockStore, MockStore } from '@ngrx/store/testing';
import { coreState, CoreState, UserActions, ActionWithPayload } from 'shared-library/core/store';
import { Utils, WindowRef } from 'shared-library/core/services';
import { MatSnackBarModule } from '@angular/material';
import { AppState } from '../../../../../../trivia/src/app/store';
import { TEST_DATA } from 'shared-library/testing/test.data';

describe('InviteMailFriendsComponent', () => {
let component: InviteMailFriendsComponent;
let fixture: ComponentFixture<InviteMailFriendsComponent>;
let mockStore: MockStore<AppState>;
let mockStore: MockStore<CoreState>;
let spy: any;
let mockCoreSelector: MemoizedSelector<CoreState, Partial<CoreState>>;

Expand All @@ -35,7 +34,7 @@ describe('InviteMailFriendsComponent', () => {
}),
UserActions,
Utils,
WindowRef,],
WindowRef, ],
declarations: [InviteMailFriendsComponent]
});

Expand Down Expand Up @@ -112,42 +111,43 @@ describe('InviteMailFriendsComponent', () => {
component.invitationForm.controls['email'].setValue('test@test');
component.onSubscribe();
expect(component.errorMsg).toBe('Following email is not valid address!');
})
});


// tslint:disable-next-line: max-line-length
it(`on Subscribe check if email is invalid then invalid email will add into invalid email list and show error msg should be false `, () => {
component.invitationForm.controls['email'].setValue('test@test');
component.onSubscribe();
expect(component.showErrorMsg).toBeTruthy();
expect(component.invalidEmailList.length).toEqual(1);
})
});

it(`on Subscribe errorMsg message should be set if wrong multiple email inserted `, () => {
component.invitationForm.controls['email'].setValue('test@test,second.mail');
component.onSubscribe();
expect(component.errorMsg).toBe('Following emails are not valid address!');
})
});


it(`on Subscribe show error message should be true set if invalid single email inserted`, () => {
component.invitationForm.controls['email'].setValue('test@test,second.mail');
component.onSubscribe();
expect(component.showErrorMsg).toBeTruthy();
expect(component.invalidEmailList.length).toEqual(2);
})
});


it(`on Subscribe invalid email should push on invalidEmailList list should 1`, () => {
component.invitationForm.controls['email'].setValue('test@test,[email protected]');
component.onSubscribe();
expect(component.invalidEmailList.length).toEqual(1);
})
});

it(`on Subscribe valid email should push on validEmail list length should be 2`, () => {
component.invitationForm.controls['email'].setValue('test@test,[email protected],[email protected]');
component.onSubscribe();
expect(component.validEmail.length).toEqual(2);
})
});

it(`on Subscribe should dispatch action to add user invitation with correct payload `, () => {
component.invitationForm.controls['email'].setValue('[email protected]');
Expand All @@ -158,7 +158,7 @@ describe('InviteMailFriendsComponent', () => {
const payloadData = {
userId: user.userId,
emails: ['[email protected]']
}
};

spy.and.callFake((action: ActionWithPayload<string>) => {
expect(action.type).toEqual(UserActions.ADD_USER_INVITATION);
Expand All @@ -167,38 +167,38 @@ describe('InviteMailFriendsComponent', () => {

component.onSubscribe();
expect(mockStore.dispatch).toHaveBeenCalled();
})
});

it(`Invitation message should set to showSuccessMsg`, () => {
const userProfileSaveStatus = "Invitation is sent on [email protected]";
const userProfileSaveStatus = 'Invitation is sent on [email protected]';
mockCoreSelector.setResult({ userProfileSaveStatus });
mockStore.refreshState();
expect(component.showSuccessMsg).toEqual(userProfileSaveStatus);
});

it(`Invitation message should not set to showSuccessMsg if it status is 'NONE'`, () => {
const userProfileSaveStatus = "NONE";
const userProfileSaveStatus = 'NONE';
mockCoreSelector.setResult({ userProfileSaveStatus });
mockStore.refreshState();
expect(component.showSuccessMsg).toBeUndefined();
});

it(`Invitation message should not set to showSuccessMsg if it status is 'IN PROCESS'`, () => {
const userProfileSaveStatus = "IN PROCESS";
const userProfileSaveStatus = 'IN PROCESS';
mockCoreSelector.setResult({ userProfileSaveStatus });
mockStore.refreshState();
expect(component.showSuccessMsg).toBeUndefined();
});

it(`Invitation message should not set to showSuccessMsg if it status is 'SUCCESS'`, () => {
const userProfileSaveStatus = "SUCCESS";
const userProfileSaveStatus = 'SUCCESS';
mockCoreSelector.setResult({ userProfileSaveStatus });
mockStore.refreshState();
expect(component.showSuccessMsg).toBeUndefined();
});

it(`Invitation message should not set to showSuccessMsg if it status is 'MAKE FRIEND SUCCESS'`, () => {
const userProfileSaveStatus = "MAKE FRIEND SUCCESS";
const userProfileSaveStatus = 'MAKE FRIEND SUCCESS';
mockCoreSelector.setResult({ userProfileSaveStatus });
mockStore.refreshState();
expect(component.showSuccessMsg).toBeUndefined();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<ng-container>
<div class="col-xs-12 textcenter clearfix">
<div>
<div *ngIf="game">
<div *ngIf="game.gameOptions.playerMode == PlayerMode.Single">
<div class="success result" *ngIf="game.winnerPlayerId && game.winnerPlayerId === user.userId">Won</div>
<div class="label result" *ngIf="game.winnerPlayerId !== user.userId">Lost</div>
Expand Down Expand Up @@ -28,7 +28,7 @@
</div>

<div class="dark">{{categoryDict[game.gameOptions.categoryIds[0]]?.categoryName.charAt(0).toUpperCase() +
categoryDict[game.gameOptions.categoryIds[0]]?.categoryName.slice(1)}}</div>
categoryDict[game.gameOptions.categoryIds[0]]?.categoryName?.slice(1) }}</div>
<div class="col-xs-12 no-padding card-bottom-spacing" *ngIf="game.gameOptions.playerMode==PlayerMode.Opponent">
<div class="col-xs-6 no-padding" *ngIf="game.winnerPlayerId === user.userId">
<app-user-card [userId]="game.winnerPlayerId" [type]="userCardType.USER_WEB_IMAGE_NAME_RECENT_GAME_VERTICAL"> </app-user-card>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { RecentGameCardComponent } from './recent-game-card.component';
import { ReactiveFormsModule, FormsModule } from '@angular/forms';
import { StoreModule, MemoizedSelector, Store } from '@ngrx/store';
import { provideMockStore, MockStore } from '@ngrx/store/testing';
import { coreState, CoreState, UserActions, categoryDictionary } from 'shared-library/core/store';
import { Utils, WindowRef } from 'shared-library/core/services';
import { MatSnackBarModule } from '@angular/material';
import { TEST_DATA } from 'shared-library/testing/test.data';
import { Game } from 'shared-library/shared/model';
import { NO_ERRORS_SCHEMA } from '@angular/core';

describe('RecentGameCardComponent', () => {
let component: RecentGameCardComponent;
let fixture: ComponentFixture<RecentGameCardComponent>;
let mockStore: MockStore<CoreState>;
let spy: any;
let mockCoreSelector: MemoizedSelector<CoreState, Partial<CoreState>>;
let mockCategorySelector: MemoizedSelector<any, {}>;

beforeEach(async(() => {

TestBed.configureTestingModule({
declarations: [RecentGameCardComponent],
schemas: [NO_ERRORS_SCHEMA],
imports: [ReactiveFormsModule, FormsModule, StoreModule.forRoot({}), MatSnackBarModule],
providers: [provideMockStore({
initialState: {},
selectors: [
{
selector: coreState,
value: {}
},
{
selector: categoryDictionary,
value: {}
}
]
}),
UserActions,
Utils,
WindowRef,],

});

fixture = TestBed.createComponent(RecentGameCardComponent);
mockStore = TestBed.get(Store);
component = fixture.componentInstance;

component.user = TEST_DATA.userList[0];
const dbModel = TEST_DATA.game[0];
component.game = Game.getViewModel(dbModel);

mockCoreSelector = mockStore.overrideSelector<CoreState, Partial<CoreState>>(coreState, {});
mockCategorySelector = mockStore.overrideSelector(categoryDictionary, {});
spy = spyOn(mockStore, 'dispatch');
fixture.detectChanges();
}));

it('should create', () => {
expect(component).toBeTruthy();
});

it('Category dictionary should be set when store emit Category dictionary', () => {
const categoryDict = TEST_DATA.categoryDictionary;
mockCategorySelector.setResult(categoryDict);
mockStore.refreshState();
expect(component.categoryDict).toBe(categoryDict);
});

it('on component load should call getOppnonentID function', () => {
spy = spyOn(component, 'getOpponentId');
component.ngOnInit();
expect(component.getOpponentId).toHaveBeenCalled();
});

it('call to getOpponentId function should return correct opponent Id for passed game', () => {
const dbModel = TEST_DATA.game[0];
const opponentId = dbModel.playerIds[1];
const game = Game.getViewModel(dbModel);
expect(component.getOpponentId(game)).toBe(opponentId);
});

it('User dictionary should be set when store emit user dictionary', () => {
const userDict = TEST_DATA.userDict;
mockCoreSelector.setResult({ userDict: userDict });
mockStore.refreshState();
expect(component.userDict).toBe(userDict);
});


});
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { User, Game, Category, PlayerMode, GameStatus, userCardType } from 'shar
import { Utils } from 'shared-library/core/services';
import { coreState, CoreState, categoryDictionary } from 'shared-library/core/store';
import { UserActions } from 'shared-library/core/store/actions';
import { AutoUnsubscribe } from 'ngx-auto-unsubscribe';
import { AutoUnsubscribe } from 'shared-library/shared/decorators';

@Component({
selector: 'recent-game-card',
Expand Down Expand Up @@ -34,8 +34,11 @@ export class RecentGameCardComponent implements OnInit, OnDestroy {
userCardType = userCardType;

constructor(private store: Store<CoreState>, private userActions: UserActions, public utils: Utils, private cd: ChangeDetectorRef) {

this.categoryDictObs = store.select(categoryDictionary);
this.subscriptions.push(this.categoryDictObs.subscribe(categoryDict => this.categoryDict = categoryDict));
this.subscriptions.push(this.categoryDictObs.subscribe(categoryDict => {
this.categoryDict = categoryDict
}));
}

ngOnInit(): void {
Expand All @@ -44,7 +47,6 @@ export class RecentGameCardComponent implements OnInit, OnDestroy {
this.userDict = userDict;
this.cd.markForCheck();
}));

if (this.game) {
this.otherUserId = this.getOpponentId(this.game);
}
Expand Down
Loading

0 comments on commit f90c7de

Please sign in to comment.