From 1d0c4bef231d4c95af781cfb0903f3924f3972b7 Mon Sep 17 00:00:00 2001 From: "patrick.flege@rabobank.nl" Date: Thu, 26 Jan 2023 08:04:44 +0100 Subject: [PATCH] Finished project --- cypress/integration/home.test.js | 75 ++------ package.json | 5 +- .../courses-card-list.component.spec.ts | 70 +++----- src/app/courses/courses.module.ts | 2 + src/app/courses/home/async-examples.spec.ts | 123 +++++-------- src/app/courses/home/home.component.spec.ts | 143 +++++---------- src/app/courses/home/home.component.ts | 5 +- .../services/calculator.service.spec.ts | 62 +++---- .../courses/services/courses.service.spec.ts | 109 +++++++++++ src/app/courses/services/courses.service.ts | 6 +- .../courses/services/courses.services.spec.ts | 169 ------------------ 11 files changed, 274 insertions(+), 495 deletions(-) create mode 100644 src/app/courses/services/courses.service.spec.ts delete mode 100644 src/app/courses/services/courses.services.spec.ts diff --git a/cypress/integration/home.test.js b/cypress/integration/home.test.js index ecd7f2ff..118bf89a 100644 --- a/cypress/integration/home.test.js +++ b/cypress/integration/home.test.js @@ -1,64 +1,11 @@ - - - -describe('Home Page', () => { - - beforeEach(() => { - - cy.fixture('courses.json').as("coursesJSON"); - - cy.server(); - - cy.route('/api/courses', "@coursesJSON").as("courses"); - - cy.visit('/'); - - }); - - it('should display a list of courses', () => { - - cy.contains("All Courses"); - - cy.wait('@courses'); - - cy.get("mat-card").should("have.length", 9); - - }); - - it('should display the advanced courses', () => { - - cy.get('.mat-tab-label').should("have.length", 2); - - cy.get('.mat-tab-label').last().click(); - - cy.get('.mat-tab-body-active .mat-card-title').its('length').should('be.gt', 1); - - cy.get('.mat-tab-body-active .mat-card-title').first() - .should('contain', "Angular Security Course"); - - }); - - -}); - - - - - - - - - - - - - - - - - - - - - - +describe("Homepage", () => { + it("should display all courses", () => { + //cy.fixture('courses.json').as('courses'); + cy.intercept('GET', 'localhost:9000/api/courses',{ + fixture: 'courses.json' + }) + cy.visit('/'); + cy.contains('All Courses') + //cy.get('mat-card').should('have.length', 9) + }) +}) diff --git a/package.json b/package.json index f8d7edb0..70277f99 100644 --- a/package.json +++ b/package.json @@ -11,11 +11,12 @@ "lint": "ng lint", "cypress:open": "cypress open", "cypress:run": "cypress run", - "build:prod": "ng build --prod", + "build:prod": "ng build --optimization", "start:prod": "http-server ./dist -a localhost -p 4200", "build-and-start:prod": "run-s build:prod start:prod", "e2e": "start-server-and-test build-and-start:prod http://localhost:4200 cypress:run" - }, + +}, "private": true, "dependencies": { "@angular/animations": "15.0.2", diff --git a/src/app/courses/courses-card-list/courses-card-list.component.spec.ts b/src/app/courses/courses-card-list/courses-card-list.component.spec.ts index c7daef26..ded535bb 100644 --- a/src/app/courses/courses-card-list/courses-card-list.component.spec.ts +++ b/src/app/courses/courses-card-list/courses-card-list.component.spec.ts @@ -1,73 +1,61 @@ -import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; +import {ComponentFixture, TestBed, waitForAsync} from '@angular/core/testing'; import {CoursesCardListComponent} from './courses-card-list.component'; -import {CoursesModule} from '../courses.module'; -import {COURSES} from '../../../../server/db-data'; -import {DebugElement} from '@angular/core'; -import {By} from '@angular/platform-browser'; -import {sortCoursesBySeqNo} from '../home/sort-course-by-seq'; -import {Course} from '../model/course'; -import {setupCourses} from '../common/setup-test-data'; +import {CommonModule} from "@angular/common"; +import {MatDialogModule} from "@angular/material/dialog"; +import {DebugElement} from "@angular/core"; +import {setupCourses} from "../common/setup-test-data"; +import {By} from "@angular/platform-browser"; +import {RouterTestingModule} from "@angular/router/testing"; describe('CoursesCardListComponent', () => { - let component: CoursesCardListComponent; - let fixture: ComponentFixture; - let el: DebugElement; + let component: CoursesCardListComponent; + let fixture: ComponentFixture; + let el: DebugElement; - beforeEach(waitForAsync(() => { - TestBed.configureTestingModule({ - imports: [CoursesModule] - }) + beforeEach(waitForAsync (()=> { + TestBed.configureTestingModule( + { + imports: [CommonModule, MatDialogModule, RouterTestingModule] + } + ) .compileComponents() - .then(() => { - - fixture = TestBed.createComponent(CoursesCardListComponent); - component = fixture.componentInstance; - el = fixture.debugElement; - - }); + .then(() => { + fixture = TestBed.createComponent(CoursesCardListComponent); + component = fixture.componentInstance; + el = fixture.debugElement; + }) })); it('should create the component', () => { - expect(component).toBeTruthy(); - }); it('should display the course list', () => { + component.courses = setupCourses(); - component.courses = setupCourses(); - - fixture.detectChanges(); - - const cards = el.queryAll(By.css(".course-card")); - - expect(cards).toBeTruthy("Could not find cards"); - expect(cards.length).toBe(12, "Unexpected number of courses"); + fixture.detectChanges(); + console.log(el.nativeElement.outerHTML); + const res = el.queryAll(By.css('.course-card')) + expect(res.length).toEqual(12); }); it('should display the first course', () => { - component.courses = setupCourses(); fixture.detectChanges(); const course = component.courses[0]; - const card = el.query(By.css(".course-card:first-child")), - title = card.query(By.css("mat-card-title")), - image = card.query(By.css("img")); - - expect(card).toBeTruthy("Could not find course card"); + const card = el.query(By.css('.course-card:first-child')); + const title = card.query(By.css('mat-card-title')); + const image = card.query(By.css('img')); expect(title.nativeElement.textContent).toBe(course.titles.description); - expect(image.nativeElement.src).toBe(course.iconUrl); - }); - }); diff --git a/src/app/courses/courses.module.ts b/src/app/courses/courses.module.ts index 304d3744..3993c86e 100644 --- a/src/app/courses/courses.module.ts +++ b/src/app/courses/courses.module.ts @@ -28,6 +28,7 @@ import {MatMomentDateModule} from '@angular/material-moment-adapter'; import {ReactiveFormsModule} from '@angular/forms'; import {CoursesService} from './services/courses.service'; import {CourseResolver} from './services/course.resolver'; +import {HttpClientTestingModule} from "@angular/common/http/testing"; @NgModule({ declarations: [ @@ -39,6 +40,7 @@ import {CourseResolver} from './services/course.resolver'; ], imports: [ CommonModule, + HttpClientTestingModule, MatMenuModule, MatButtonModule, MatToolbarModule, diff --git a/src/app/courses/home/async-examples.spec.ts b/src/app/courses/home/async-examples.spec.ts index 36175bae..fbc01080 100644 --- a/src/app/courses/home/async-examples.spec.ts +++ b/src/app/courses/home/async-examples.spec.ts @@ -1,137 +1,102 @@ import {fakeAsync, flush, flushMicrotasks, tick} from '@angular/core/testing'; -import {of} from 'rxjs'; -import {delay} from 'rxjs/operators'; +import {of} from "rxjs"; +import {delay} from "rxjs/operators"; -describe('Async Testing Examples', () => { - - it('Asynchronous test example with Jasmine done()', (done: DoneFn) => { - let test = false; - - setTimeout(() => { +describe('Async Testing Examples', () => { - console.log('running assertions'); + it('Asynchronous test example with Jasmine done()', (done) => { - test = true; + let flag = false; - expect(test).toBeTruthy(); + setTimeout(()=>{ + flag = true; - done(); + console.log('Am in timeout-callback right now!'); - }, 1000); + expect(flag).toBe(true); + done(); + }, 500) }); it('Asynchronous test example - setTimeout()', fakeAsync(() => { - let test = false; - - setTimeout(() => { - }); - - setTimeout(() => { - - console.log('running assertions setTimeout()'); - - test = true; - - }, 1000); - - flush(); - - expect(test).toBeTruthy(); + let test = false; + setTimeout(() => { + console.log('In async timeout'); + test = true; + }, 100000000); + flush(); + expect(test).toBe(true) })); it('Asynchronous test example - plain Promise', fakeAsync(() => { + let test = false; - let test = false; - - console.log('Creating promise'); - - Promise.resolve().then(() => { + console.log('Outside promise'); - console.log('Promise first then() evaluated successfully'); + Promise.resolve().then(()=>{ + console.log('Inside promise') + test = true; + }) - return Promise.resolve(); - }) - .then(() => { - - console.log('Promise second then() evaluated successfully'); - - test = true; - - }); - - flushMicrotasks(); - - console.log('Running test assertions'); - - expect(test).toBeTruthy(); + flushMicrotasks(); + expect(test).toBe(true); })); it('Asynchronous test example - Promises + setTimeout()', fakeAsync(() => { - let counter = 0; - - Promise.resolve() - .then(() => { + let counter = 0; - counter+=10; + console.log('Outside async - operations'); - setTimeout(() => { + Promise.resolve().then(() => { - counter += 1; + console.log('In Promise'); - }, 1000); + counter += 10; - }); - - expect(counter).toBe(0); + setTimeout(() => { + console.log('In timeout'); + counter += 1; + }, 1000); + }); - flushMicrotasks(); + expect(counter).toBe(0); - expect(counter).toBe(10); + flushMicrotasks() - tick(500); + expect(counter).toBe(10); - expect(counter).toBe(10); + tick(500); - tick(500); + expect(counter).toBe(10); - expect(counter).toBe(11); + tick(500); + expect(counter).toBe(11); })); it('Asynchronous test example - Observables', fakeAsync(() => { - let test = false; - console.log('Creating Observable'); - const test$ = of(test).pipe(delay(1000)); test$.subscribe(() => { - - test = true; - + test = true; }); tick(1000); - console.log('Running test assertions'); - expect(test).toBe(true); - - })); - - }); diff --git a/src/app/courses/home/home.component.spec.ts b/src/app/courses/home/home.component.spec.ts index 75dc1c9a..51e3647b 100644 --- a/src/app/courses/home/home.component.spec.ts +++ b/src/app/courses/home/home.component.spec.ts @@ -1,57 +1,37 @@ import { ComponentFixture, fakeAsync, flush, flushMicrotasks, TestBed, tick, waitForAsync } from '@angular/core/testing'; import {CoursesModule} from '../courses.module'; import {DebugElement} from '@angular/core'; - import {HomeComponent} from './home.component'; -import {HttpClientTestingModule, HttpTestingController} from '@angular/common/http/testing'; import {CoursesService} from '../services/courses.service'; -import {HttpClient} from '@angular/common/http'; -import {COURSES} from '../../../../server/db-data'; -import {setupCourses} from '../common/setup-test-data'; -import {By} from '@angular/platform-browser'; -import {of} from 'rxjs'; import {NoopAnimationsModule} from '@angular/platform-browser/animations'; -import {click} from '../common/test-utils'; - - - +import {setupCourses} from "../common/setup-test-data"; +import {By} from "@angular/platform-browser"; +import {of} from "rxjs"; describe('HomeComponent', () => { - let fixture: ComponentFixture; - let component:HomeComponent; + let component: HomeComponent; let el: DebugElement; - let coursesService: any; - - const beginnerCourses = setupCourses() - .filter(course => course.category == 'BEGINNER'); - - const advancedCourses = setupCourses() - .filter(course => course.category == 'ADVANCED'); - + let fixture: ComponentFixture; + let coursesServiceSpy: any; + const beginnerCourses = setupCourses().filter(course => course.category === 'BEGINNER'); + const advancedCourses = setupCourses().filter(course => course.category === 'ADVANCED'); beforeEach(waitForAsync(() => { - - const coursesServiceSpy = jasmine.createSpyObj('CoursesService', ['findAllCourses']) - - TestBed.configureTestingModule({ - imports: [ - CoursesModule, - NoopAnimationsModule - ], - providers: [ - {provide: CoursesService, useValue: coursesServiceSpy} - ] - }).compileComponents() - .then(() => { - fixture = TestBed.createComponent(HomeComponent); - component = fixture.componentInstance; - el = fixture.debugElement; - coursesService = TestBed.get(CoursesService); - }); - - })); + TestBed.configureTestingModule({ + imports: [CoursesModule, NoopAnimationsModule], + providers: [{ + provide: CoursesService, + useValue: jasmine.createSpyObj('CoursesService', ['findAllCourses'])}] + }).compileComponents().then(() =>{ + fixture = TestBed.createComponent(HomeComponent); + component = fixture.componentInstance; + el = fixture.debugElement; + } + ); + coursesServiceSpy = TestBed.inject(CoursesService); + })) it("should create the component", () => { @@ -61,96 +41,63 @@ describe('HomeComponent', () => { it("should display only beginner courses", () => { + coursesServiceSpy.findAllCourses.and.returnValue(of(beginnerCourses)); - coursesService.findAllCourses.and.returnValue(of(beginnerCourses)); - - fixture.detectChanges(); - - const tabs = el.queryAll(By.css(".mdc-tab")); + fixture.detectChanges(); - expect(tabs.length).toBe(1, "Unexpected number of tabs found"); + const beginnerCoursesTabs = el.queryAll(By.css('.mdc-tab')); + expect(beginnerCoursesTabs.length).withContext('Found more tabs than expected').toBe(1); }); it("should display only advanced courses", () => { - - coursesService.findAllCourses.and.returnValue(of(advancedCourses)); + coursesServiceSpy.findAllCourses.and.returnValue(of(advancedCourses)); fixture.detectChanges(); - const tabs = el.queryAll(By.css(".mdc-tab")); - - expect(tabs.length).toBe(1, "Unexpected number of tabs found"); + const advancedCoursesTabs = el.queryAll(By.css('.mdc-tab')); + expect(advancedCoursesTabs.length).withContext('Found more tabs than expected').toBe(1); }); it("should display both tabs", () => { + coursesServiceSpy.findAllCourses.and.returnValue(of(setupCourses())); - coursesService.findAllCourses.and.returnValue(of(setupCourses())); - - fixture.detectChanges(); - - const tabs = el.queryAll(By.css(".mdc-tab")); + fixture.detectChanges(); - expect(tabs.length).toBe(2, "Expected to find 2 tabs"); + const bothCoursesTabs = el.queryAll(By.css('.mdc-tab')); + expect(bothCoursesTabs.length).withContext('Found more tabs than expected').toBe(2) }); - it("should display advanced courses when tab clicked - fakeAsync", fakeAsync(() => { - - coursesService.findAllCourses.and.returnValue(of(setupCourses())); + fit("should display advanced courses when tab clicked - fakeAsync", fakeAsync(() => { + coursesServiceSpy.findAllCourses.and.returnValue(of(setupCourses())); fixture.detectChanges(); - const tabs = el.queryAll(By.css(".mdc-tab")); + const tabs = el.queryAll(By.css('.mdc-tab')); - click(tabs[1]); + tabs[1].nativeElement.click(); fixture.detectChanges(); - flush(); - - const cardTitles = el.queryAll(By.css('.mat-mdc-tab-body-active .mat-mdc-card-title')); - - console.log(cardTitles); - - expect(cardTitles.length).toBeGreaterThan(0,"Could not find card titles"); + tick(1000); + const displayedCourses = el.queryAll(By.css('.mat-mdc-card-title')); - expect(cardTitles[0].nativeElement.textContent).toContain("Angular Security Course"); + expect(displayedCourses.length).toBeGreaterThan(0); + expect(displayedCourses[0].nativeElement.textContent).toEqual('Angular Testing Course'); })); - it("should display advanced courses when tab clicked - async", waitForAsync(() => { - - coursesService.findAllCourses.and.returnValue(of(setupCourses())); - - fixture.detectChanges(); - - const tabs = el.queryAll(By.css(".mdc-tab")); - - click(tabs[1]); - - fixture.detectChanges(); - - fixture.whenStable().then(() => { - - console.log("called whenStable() "); - - const cardTitles = el.queryAll(By.css('.mat-mdc-tab-body-active .mat-mdc-card-title')); - - expect(cardTitles.length).toBeGreaterThan(0,"Could not find card titles"); - - expect(cardTitles[0].nativeElement.textContent).toContain("Angular Security Course"); - - }); - - })); - - + // it("should display advanced courses when tab clicked - async", waitForAsync(() => { + // + // pending(); + // + // })); }); diff --git a/src/app/courses/home/home.component.ts b/src/app/courses/home/home.component.ts index 689c6cdc..259af465 100644 --- a/src/app/courses/home/home.component.ts +++ b/src/app/courses/home/home.component.ts @@ -22,6 +22,8 @@ export class HomeComponent implements OnInit { ngOnInit() { + console.log('Called ngOnInit()'); + this.reloadCourses(); } @@ -32,9 +34,10 @@ export class HomeComponent implements OnInit { const courses$ = this.coursesService.findAllCourses(); this.beginnerCourses$ = this.filterByCategory(courses$, 'BEGINNER'); + this.beginnerCourses$.subscribe(course => console.log(course)) this.advancedCourses$ = this.filterByCategory(courses$, 'ADVANCED'); - + this.advancedCourses$.subscribe(course => console.log(course)) } filterByCategory(courses$: Observable, category:string) { diff --git a/src/app/courses/services/calculator.service.spec.ts b/src/app/courses/services/calculator.service.spec.ts index e13e263a..dc506af0 100644 --- a/src/app/courses/services/calculator.service.spec.ts +++ b/src/app/courses/services/calculator.service.spec.ts @@ -1,53 +1,37 @@ import {CalculatorService} from './calculator.service'; -import {LoggerService} from './logger.service'; -import {TestBed} from '@angular/core/testing'; - +import {LoggerService} from "./logger.service"; +import {TestBed} from "@angular/core/testing"; describe('CalculatorService', () => { - let calculator: CalculatorService, - loggerSpy: any; - - beforeEach(()=> { - - console.log("Calling beforeEach"); - - loggerSpy = jasmine.createSpyObj('LoggerService', ["log"]); - - TestBed.configureTestingModule({ - providers: [ - CalculatorService, - {provide: LoggerService, useValue: loggerSpy} - ] - }); - - calculator = TestBed.get(CalculatorService); - - }); - - it('should add two numbers', () => { - - console.log("add test"); - - const result = calculator.add(2, 2); - - expect(result).toBe(4); - - expect(loggerSpy.log).toHaveBeenCalledTimes(1); + let calculatorService: CalculatorService, loggerSpy: any, testBed: TestBed; + beforeEach(() => { + loggerSpy = jasmine.createSpyObj('LoggerService', ['log']); + TestBed.configureTestingModule({ + providers: [ + {provide: LoggerService, useValue: loggerSpy}, + CalculatorService + ] }); + calculatorService = TestBed.inject(CalculatorService); - it('should subtract two numbers', () => { + }); - console.log("subtract test"); + xit('should add up two numbers.', () => { - const result = calculator.subtract(2, 2); + const additionResult = calculatorService.add(2, 2); - expect(result).toBe(0, "unexpected subtraction result"); + expect(loggerSpy.log).toHaveBeenCalledTimes(1); + expect(additionResult).toBe(4) + }) - expect(loggerSpy.log).toHaveBeenCalledTimes(1); + it('should subtract two numbers.', () => { - }); + const additionResult = calculatorService.subtract(2, 2); -}); \ No newline at end of file + expect(loggerSpy.log).toHaveBeenCalledTimes(1); + expect(additionResult).toBe(0) + }) +}); diff --git a/src/app/courses/services/courses.service.spec.ts b/src/app/courses/services/courses.service.spec.ts new file mode 100644 index 00000000..a65538b7 --- /dev/null +++ b/src/app/courses/services/courses.service.spec.ts @@ -0,0 +1,109 @@ +import {TestBed} from "@angular/core/testing"; +import {HttpClientTestingModule, HttpTestingController} from "@angular/common/http/testing"; +import {CoursesService} from "./courses.service"; +import {COURSES, findLessonsForCourse} from "../../../../server/db-data"; +import {Course} from "../model/course"; +import {HttpErrorResponse} from "@angular/common/http"; + +describe("CoursesService", () =>{ + + let httpController: HttpTestingController, coursesService: CoursesService; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [HttpClientTestingModule], + providers: [ + CoursesService, + ] + }) + + coursesService = TestBed.inject(CoursesService); + httpController = TestBed.inject(HttpTestingController); + }); + it('should retrieve all courses', () => { + coursesService.findAllCourses().subscribe(courses => { + expect(courses).toBeTruthy(); + expect(courses.length).toEqual(12); + const course = courses.find(course => course.id == 12); + expect(course.titles.description).toBe("Angular Testing Course"); + }) + + const req = httpController.expectOne('/api/courses'); + + expect(req.request.method).toEqual("GET") + + req.flush({payload: Object.values(COURSES)}); + }) + + it('should test find course by Id', () => { + coursesService.findCourseById(12).subscribe(course => { + expect(course).toBeTruthy(); + expect(course.id).toEqual(12) + }); + + const req = httpController.expectOne('/api/courses/12'); + expect(req.request.method).toEqual('GET'); + req.flush(COURSES[12]); + }) + + it('should return the modified object after "save"-operation', ()=>{ + const changes: Partial = { + titles: { + description: 'Newly saved course' + } + }; + + coursesService.saveCourse(12, changes).subscribe(course => { + expect(course.id).toEqual(12); + expect(course.titles.description).toEqual(changes.titles.description) + }) + + const req = httpController.expectOne('/api/courses/12'); + expect(req.request.method).toEqual('PUT'); + req.flush({ + ...COURSES[12], + ...changes + }) + }) + + it('should throw an error when trying to save a new course', ()=> { + const changes: Partial = { + titles: { + description: 'Newly saved course' + } + }; + + coursesService.saveCourse(12, changes).subscribe(() => { + fail('Should return an http-error'); + }, error => { + expect(error).toBeInstanceOf(HttpErrorResponse); + expect(error.status).toEqual(500) + expect(error.statusText).toEqual('Http-request failed'); + } + ); + + const req = httpController.expectOne('/api/courses/12'); + + expect(req.request.method).toEqual('PUT'); + + req.flush('Save course failed', { + status: 500, statusText: 'Http-request failed' + }); + }); + + it('Should return a lesson afterwards', () => { + coursesService.findLessons(12).subscribe(lesson => { + expect(lesson).toBeTruthy(); + expect(lesson.length).toEqual(3); + }); + + const req = httpController.expectOne('/api/lessons?courseId=12&filter=&sortOrder=asc&pageNumber=0&pageSize=3'); + + expect(req.request.method).toEqual('GET') + + req.flush({payload: Object.values(findLessonsForCourse(12)).slice(0,3)}) + }) + afterEach(() => { + httpController.verify(); + }) +}) diff --git a/src/app/courses/services/courses.service.ts b/src/app/courses/services/courses.service.ts index 9ee69d95..ea115bf2 100644 --- a/src/app/courses/services/courses.service.ts +++ b/src/app/courses/services/courses.service.ts @@ -3,7 +3,7 @@ import {Injectable} from "@angular/core"; import {HttpClient, HttpParams} from "@angular/common/http"; import {Observable} from "rxjs"; -import {map} from "rxjs/operators"; +import {map, tap} from "rxjs/operators"; import {Lesson} from "../model/lesson"; import {Course} from '../model/course'; @@ -20,9 +20,11 @@ export class CoursesService { } findAllCourses(): Observable { + console.log('In find all courses') return this.http.get('/api/courses') .pipe( - map(res => res['payload']) + map(res => res['payload']), + tap(res => console.log(res)) ); } diff --git a/src/app/courses/services/courses.services.spec.ts b/src/app/courses/services/courses.services.spec.ts deleted file mode 100644 index 44922f92..00000000 --- a/src/app/courses/services/courses.services.spec.ts +++ /dev/null @@ -1,169 +0,0 @@ -import {CoursesService} from './courses.service'; -import {TestBed} from '@angular/core/testing'; -import {HttpClientTestingModule, HttpTestingController} from '@angular/common/http/testing'; -import {COURSES, findLessonsForCourse} from '../../../../server/db-data'; -import {Course} from '../model/course'; -import {HttpErrorResponse} from '@angular/common/http'; - - -describe('CoursesService', () => { - - let coursesService: CoursesService, - httpTestingController: HttpTestingController; - - beforeEach(() => { - - TestBed.configureTestingModule({ - imports: [ - HttpClientTestingModule - ], - providers: [ - CoursesService - ] - }); - - coursesService = TestBed.get(CoursesService), - httpTestingController = TestBed.get(HttpTestingController); - - }); - - it('should retrieve all courses', () => { - - coursesService.findAllCourses() - .subscribe(courses => { - - expect(courses).toBeTruthy('No courses returned'); - - expect(courses.length).toBe(12, - "incorrect number of courses"); - - const course = courses.find(course => course.id == 12); - - expect(course.titles.description).toBe( - "Angular Testing Course"); - - }); - - const req = httpTestingController.expectOne('/api/courses'); - - expect(req.request.method).toEqual("GET"); - - req.flush({payload: Object.values(COURSES)}); - - }); - - it('should find a course by id', () => { - - coursesService.findCourseById(12) - .subscribe(course => { - - expect(course).toBeTruthy(); - expect(course.id).toBe(12); - - }); - - const req = httpTestingController.expectOne('/api/courses/12'); - - expect(req.request.method).toEqual("GET"); - - req.flush(COURSES[12]); - - }); - - it('should save the course data', () => { - - const changes :Partial = - {titles:{description: 'Testing Course'}}; - - coursesService.saveCourse(12, changes) - .subscribe(course => { - - expect(course.id).toBe(12); - - }); - - const req = httpTestingController.expectOne('/api/courses/12'); - - expect(req.request.method).toEqual("PUT"); - - expect(req.request.body.titles.description) - .toEqual(changes.titles.description); - - req.flush({ - ...COURSES[12], - ...changes - }) - - }); - - it('should give an error if save course fails', () => { - - const changes :Partial = - {titles:{description: 'Testing Course'}}; - - coursesService.saveCourse(12, changes) - .subscribe( - () => fail("the save course operation should have failed"), - - (error: HttpErrorResponse) => { - expect(error.status).toBe(500); - } - ); - - const req = httpTestingController.expectOne('/api/courses/12'); - - expect(req.request.method).toEqual("PUT"); - - req.flush('Save course failed', {status:500, - statusText:'Internal Server Error'}); - }); - - it('should find a list of lessons', () => { - - coursesService.findLessons(12) - .subscribe(lessons => { - - expect(lessons).toBeTruthy(); - - expect(lessons.length).toBe(3); - - }); - - const req = httpTestingController.expectOne( - req => req.url == '/api/lessons'); - - expect(req.request.method).toEqual("GET"); - expect(req.request.params.get("courseId")).toEqual("12"); - expect(req.request.params.get("filter")).toEqual(""); - expect(req.request.params.get("sortOrder")).toEqual("asc"); - expect(req.request.params.get("pageNumber")).toEqual("0"); - expect(req.request.params.get("pageSize")).toEqual("3"); - - req.flush({ - payload: findLessonsForCourse(12).slice(0,3) - }); - - - }); - - afterEach(() => { - - httpTestingController.verify(); - }); - -}); - - - - - - - - - - - - - - -