Skip to content

Commit 92ff1f7

Browse files
committed
mocking child components
1 parent 6ef3bc7 commit 92ff1f7

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
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

Comments
 (0)