|
| 1 | +import { ComponentFixture, TestBed } from "@angular/core/testing"; |
| 2 | +import { HeroesComponent } from "./heroes.component"; |
| 3 | +import { NO_ERRORS_SCHEMA, Input, Component } from "@angular/core"; |
| 4 | +import { HeroService } from "../hero.service"; |
| 5 | +import { of } from "rxjs"; |
| 6 | +import { Hero } from "../hero"; |
| 7 | + |
| 8 | +describe("Heroes Components (shallow test)", () => { |
| 9 | + let fixture: ComponentFixture<HeroesComponent>; |
| 10 | + let mockHeroService; |
| 11 | + let HEROES; |
| 12 | + |
| 13 | + @Component({ |
| 14 | + selector: "app-hero", |
| 15 | + template: "./hero.component.html" |
| 16 | + }) |
| 17 | + class FakeHeroComponent { |
| 18 | + @Input() hero: Hero; |
| 19 | + //@Output() delete = new EventEmitter(); |
| 20 | + } |
| 21 | + |
| 22 | + beforeEach(() => { |
| 23 | + //Has the same classes as the original service |
| 24 | + mockHeroService = jasmine.createSpyObj([ |
| 25 | + "getHeroes", |
| 26 | + "addHero", |
| 27 | + "deleteHero" |
| 28 | + ]); |
| 29 | + |
| 30 | + HEROES = [ |
| 31 | + { id: 1, name: "SpiderDule", strength: 8 }, |
| 32 | + { id: 2, name: "SpiderDule", strength: 8 }, |
| 33 | + { id: 3, name: "SpiderDule", strength: 8 } |
| 34 | + ]; |
| 35 | + |
| 36 | + TestBed.configureTestingModule({ |
| 37 | + declarations: [HeroesComponent, FakeHeroComponent], |
| 38 | + providers: [{ provide: HeroService, useValue: mockHeroService }] //Long hand provider sintax by telling angular to mock the provider |
| 39 | + // schemas: [NO_ERRORS_SCHEMA] |
| 40 | + }); |
| 41 | + |
| 42 | + fixture = TestBed.createComponent(HeroesComponent); |
| 43 | + }); |
| 44 | + |
| 45 | + //Test a component that has a service and a child component |
| 46 | + it("should set heroes correctly from the service", () => { |
| 47 | + mockHeroService.getHeroes.and.returnValue(of(HEROES)); |
| 48 | + fixture.detectChanges(); //run this to trigger the ngOnit() |
| 49 | + |
| 50 | + expect(fixture.componentInstance.heroes.length).toBe(3); |
| 51 | + }); |
| 52 | +}); |
0 commit comments