_id
stringlengths
21
254
text
stringlengths
1
93.7k
metadata
dict
angular/adev/src/content/examples/testing/src/app/shared/highlight.directive.spec.ts_0_3657
import {Component, DebugElement} from '@angular/core'; import {ComponentFixture, TestBed} from '@angular/core/testing'; import {By} from '@angular/platform-browser'; import {HighlightDirective} from './highlight.directive'; // #docregion test-component @Component({ standalone: true, template: ` <h2 highlight="yellow">Something Yellow</h2> <h2 highlight>The Default (Gray)</h2> <h2>No Highlight</h2> <input #box [highlight]="box.value" value="cyan" />`, imports: [HighlightDirective], }) class TestComponent {} // #enddocregion test-component describe('HighlightDirective', () => { let fixture: ComponentFixture<TestComponent>; let des: DebugElement[]; // the three elements w/ the directive let bareH2: DebugElement; // the <h2> w/o the directive // #docregion selected-tests beforeEach(() => { fixture = TestBed.configureTestingModule({ imports: [HighlightDirective, TestComponent], }).createComponent(TestComponent); fixture.detectChanges(); // initial binding // all elements with an attached HighlightDirective des = fixture.debugElement.queryAll(By.directive(HighlightDirective)); // the h2 without the HighlightDirective bareH2 = fixture.debugElement.query(By.css('h2:not([highlight])')); }); // color tests it('should have three highlighted elements', () => { expect(des.length).toBe(3); }); it('should color 1st <h2> background "yellow"', () => { const bgColor = des[0].nativeElement.style.backgroundColor; expect(bgColor).toBe('yellow'); }); it('should color 2nd <h2> background w/ default color', () => { const dir = des[1].injector.get(HighlightDirective) as HighlightDirective; const bgColor = des[1].nativeElement.style.backgroundColor; expect(bgColor).toBe(dir.defaultColor); }); it('should bind <input> background to value color', () => { // easier to work with nativeElement const input = des[2].nativeElement as HTMLInputElement; expect(input.style.backgroundColor).withContext('initial backgroundColor').toBe('cyan'); input.value = 'green'; // Dispatch a DOM event so that Angular responds to the input value change. input.dispatchEvent(new Event('input')); fixture.detectChanges(); expect(input.style.backgroundColor).withContext('changed backgroundColor').toBe('green'); }); it('bare <h2> should not have a customProperty', () => { expect(bareH2.properties['customProperty']).toBeUndefined(); }); // #enddocregion selected-tests // Removed on 12/02/2016 when ceased public discussion of the `Renderer`. Revive in future? // // customProperty tests // it('all highlighted elements should have a true customProperty', () => { // const allTrue = des.map(de => !!de.properties['customProperty']).every(v => v === true); // expect(allTrue).toBe(true); // }); // injected directive // attached HighlightDirective can be injected it('can inject `HighlightDirective` in 1st <h2>', () => { const dir = des[0].injector.get(HighlightDirective); expect(dir).toBeTruthy(); }); it('cannot inject `HighlightDirective` in 3rd <h2>', () => { const dir = bareH2.injector.get(HighlightDirective, null); expect(dir).toBe(null); }); // DebugElement.providerTokens // attached HighlightDirective should be listed in the providerTokens it('should have `HighlightDirective` in 1st <h2> providerTokens', () => { expect(des[0].providerTokens).toContain(HighlightDirective); }); it('should not have `HighlightDirective` in 3rd <h2> providerTokens', () => { expect(bareH2.providerTokens).not.toContain(HighlightDirective); }); });
{ "end_byte": 3657, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/shared/highlight.directive.spec.ts" }
angular/adev/src/content/examples/testing/src/app/shared/shared.ts_0_290
import {FormsModule} from '@angular/forms'; import {HighlightDirective} from './highlight.directive'; import {TitleCasePipe} from './title-case.pipe'; import {NgFor, NgIf} from '@angular/common'; export const sharedImports = [FormsModule, HighlightDirective, TitleCasePipe, NgIf, NgFor];
{ "end_byte": 290, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/shared/shared.ts" }
angular/adev/src/content/examples/testing/src/app/shared/title-case.pipe.ts_0_439
// #docregion import {Pipe, PipeTransform} from '@angular/core'; @Pipe({name: 'titlecase', standalone: true, pure: true}) /** Transform to Title Case: uppercase the first letter of the words in a string. */ export class TitleCasePipe implements PipeTransform { transform(input: string): string { return input.length === 0 ? '' : input.replace(/\w\S*/g, (txt) => txt[0].toUpperCase() + txt.slice(1).toLowerCase()); } }
{ "end_byte": 439, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/shared/title-case.pipe.ts" }
angular/adev/src/content/examples/testing/src/app/shared/canvas.component.ts_0_1121
// #docplaster // #docregion import-canvas-patch // Import patch to make async `HTMLCanvasElement` methods (such as `.toBlob()`) Zone.js-aware. // Either import in `polyfills.ts` (if used in more than one places in the app) or in the component // file using `HTMLCanvasElement` (if it is only used in a single file). import 'zone.js/plugins/zone-patch-canvas'; // #enddocregion import-canvas-patch // #docregion main import {Component, AfterViewInit, ViewChild, ElementRef} from '@angular/core'; @Component({ standalone: true, selector: 'sample-canvas', template: '<canvas #sampleCanvas width="200" height="200"></canvas>', }) export class CanvasComponent implements AfterViewInit { blobSize = 0; @ViewChild('sampleCanvas') sampleCanvas!: ElementRef; ngAfterViewInit() { const canvas: HTMLCanvasElement = this.sampleCanvas.nativeElement; const context = canvas.getContext('2d')!; context.clearRect(0, 0, 200, 200); context.fillStyle = '#FF1122'; context.fillRect(0, 0, 200, 200); canvas.toBlob((blob) => { this.blobSize = blob?.size ?? 0; }); } } // #enddocregion main
{ "end_byte": 1121, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/shared/canvas.component.ts" }
angular/adev/src/content/examples/testing/src/app/about/about.component.spec.ts_0_979
import {provideHttpClient} from '@angular/common/http'; import {CUSTOM_ELEMENTS_SCHEMA} from '@angular/core'; import {ComponentFixture, TestBed} from '@angular/core/testing'; import {UserService} from '../model'; import {TwainService} from '../twain/twain.service'; import {AboutComponent} from './about.component'; let fixture: ComponentFixture<AboutComponent>; describe('AboutComponent (highlightDirective)', () => { // #docregion tests beforeEach(() => { fixture = TestBed.configureTestingModule({ imports: [AboutComponent], providers: [provideHttpClient(), TwainService, UserService], schemas: [CUSTOM_ELEMENTS_SCHEMA], }).createComponent(AboutComponent); fixture.detectChanges(); // initial binding }); it('should have skyblue <h2>', () => { const h2: HTMLElement = fixture.nativeElement.querySelector('h2'); const bgColor = h2.style.backgroundColor; expect(bgColor).toBe('skyblue'); }); // #enddocregion tests });
{ "end_byte": 979, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/about/about.component.spec.ts" }
angular/adev/src/content/examples/testing/src/app/about/about.component.ts_0_417
// #docregion import {Component} from '@angular/core'; import {HighlightDirective} from '../shared/highlight.directive'; import {TwainComponent} from '../twain/twain.component'; @Component({ standalone: true, template: ` <h2 highlight="skyblue">About</h2> <h3>Quote of the day:</h3> <twain-quote></twain-quote> `, imports: [TwainComponent, HighlightDirective], }) export class AboutComponent {}
{ "end_byte": 417, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/about/about.component.ts" }
angular/adev/src/content/examples/testing/src/app/welcome/welcome.component.spec.ts_0_2609
// #docplaster import {ComponentFixture, inject, TestBed} from '@angular/core/testing'; import {UserService} from '../model/user.service'; import {WelcomeComponent} from './welcome.component'; // #docregion mock-user-service class MockUserService { isLoggedIn = true; user = {name: 'Test User'}; } // #enddocregion mock-user-service describe('WelcomeComponent', () => { let comp: WelcomeComponent; let fixture: ComponentFixture<WelcomeComponent>; let componentUserService: UserService; // the actually injected service let userService: UserService; // the TestBed injected service let el: HTMLElement; // the DOM element with the welcome message // #docregion setup beforeEach(() => { fixture = TestBed.createComponent(WelcomeComponent); fixture.autoDetectChanges(); comp = fixture.componentInstance; // #docregion injected-service // UserService actually injected into the component userService = fixture.debugElement.injector.get(UserService); // #enddocregion injected-service componentUserService = userService; // #docregion inject-from-testbed // UserService from the root injector userService = TestBed.inject(UserService); // #enddocregion inject-from-testbed // get the "welcome" element by CSS selector (e.g., by class name) el = fixture.nativeElement.querySelector('.welcome'); }); // #enddocregion setup // #docregion tests it('should welcome the user', async () => { await fixture.whenStable(); const content = el.textContent; expect(content).withContext('"Welcome ..."').toContain('Welcome'); expect(content).withContext('expected name').toContain('Test User'); }); it('should welcome "Bubba"', async () => { userService.user.set({name: 'Bubba'}); // welcome message hasn't been shown yet await fixture.whenStable(); expect(el.textContent).toContain('Bubba'); }); it('should request login if not logged in', async () => { userService.isLoggedIn.set(false); // welcome message hasn't been shown yet await fixture.whenStable(); const content = el.textContent; expect(content).withContext('not welcomed').not.toContain('Welcome'); expect(content) .withContext('"log in"') .toMatch(/log in/i); }); // #enddocregion tests it("should inject the component's UserService instance", inject( [UserService], (service: UserService) => { expect(service).toBe(componentUserService); }, )); it('TestBed and Component UserService should be the same', () => { expect(userService).toBe(componentUserService); }); });
{ "end_byte": 2609, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/welcome/welcome.component.spec.ts" }
angular/adev/src/content/examples/testing/src/app/welcome/welcome.component.ts_0_573
// #docregion import {Component, OnInit, signal} from '@angular/core'; import {UserService} from '../model/user.service'; @Component({ standalone: true, selector: 'app-welcome', template: '<h3 class="welcome"><i>{{welcome()}}</i></h3>', }) // #docregion class export class WelcomeComponent implements OnInit { welcome = signal(''); constructor(private userService: UserService) {} ngOnInit(): void { this.welcome.set( this.userService.isLoggedIn() ? 'Welcome, ' + this.userService.user().name : 'Please log in.', ); } } // #enddocregion class
{ "end_byte": 573, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/welcome/welcome.component.ts" }
angular/adev/src/content/examples/testing/src/app/dashboard/dashboard.component.no-testbed.spec.ts_0_1909
import {Router} from '@angular/router'; import {DashboardComponent} from './dashboard.component'; import {Hero} from '../model/hero'; import {addMatchers} from '../../testing'; import {TestHeroService} from '../model/testing/test-hero.service'; class FakeRouter { navigateByUrl(url: string) { return url; } } describe('DashboardComponent class only', () => { let comp: DashboardComponent; let heroService: TestHeroService; let router: Router; beforeEach(() => { addMatchers(); router = new FakeRouter() as any as Router; heroService = new TestHeroService(); comp = new DashboardComponent(router, heroService); }); it('should NOT have heroes before calling OnInit', () => { expect(comp.heroes.length).withContext('should not have heroes before OnInit').toBe(0); }); it('should NOT have heroes immediately after OnInit', () => { comp.ngOnInit(); // ngOnInit -> getHeroes expect(comp.heroes.length) .withContext('should not have heroes until service promise resolves') .toBe(0); }); it('should HAVE heroes after HeroService gets them', (done: DoneFn) => { comp.ngOnInit(); // ngOnInit -> getHeroes heroService.lastResult // the one from getHeroes .subscribe({ next: () => { // throw new Error('deliberate error'); // see it fail gracefully expect(comp.heroes.length) .withContext('should have heroes after service promise resolves') .toBeGreaterThan(0); done(); }, error: done.fail, }); }); it('should tell ROUTER to navigate by hero id', () => { const hero: Hero = {id: 42, name: 'Abbracadabra'}; const spy = spyOn(router, 'navigateByUrl'); comp.gotoDetail(hero); const navArgs = spy.calls.mostRecent().args[0]; expect(navArgs).withContext('should nav to HeroDetail for Hero 42').toBe('/heroes/42'); }); });
{ "end_byte": 1909, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/dashboard/dashboard.component.no-testbed.spec.ts" }
angular/adev/src/content/examples/testing/src/app/dashboard/dashboard.component.spec.ts_0_4176
import {provideHttpClient} from '@angular/common/http'; import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing'; import {NO_ERRORS_SCHEMA} from '@angular/core'; import {TestBed, waitForAsync} from '@angular/core/testing'; import {By} from '@angular/platform-browser'; import {NavigationEnd, provideRouter, Router} from '@angular/router'; import {RouterTestingHarness} from '@angular/router/testing'; import {firstValueFrom} from 'rxjs'; import {filter} from 'rxjs/operators'; import {addMatchers, click} from '../../testing'; import {HeroService} from '../model/hero.service'; import {getTestHeroes} from '../model/testing/test-heroes'; import {DashboardComponent} from './dashboard.component'; import {appConfig} from '../app.config'; import {HeroDetailComponent} from '../hero/hero-detail.component'; beforeEach(addMatchers); let comp: DashboardComponent; let harness: RouterTestingHarness; //////// Deep //////////////// describe('DashboardComponent (deep)', () => { compileAndCreate(); tests(clickForDeep); function clickForDeep() { // get first <div class="hero"> const heroEl: HTMLElement = harness.routeNativeElement!.querySelector('.hero')!; click(heroEl); return firstValueFrom( TestBed.inject(Router).events.pipe(filter((e) => e instanceof NavigationEnd)), ); } }); //////// Shallow //////////////// describe('DashboardComponent (shallow)', () => { beforeEach(() => { TestBed.configureTestingModule( Object.assign({}, appConfig, { imports: [DashboardComponent, HeroDetailComponent], providers: [provideRouter([{path: 'heroes/:id', component: HeroDetailComponent}])], schemas: [NO_ERRORS_SCHEMA], }), ); }); compileAndCreate(); tests(clickForShallow); function clickForShallow() { // get first <dashboard-hero> DebugElement const heroDe = harness.routeDebugElement!.query(By.css('dashboard-hero')); heroDe.triggerEventHandler('selected', comp.heroes[0]); return Promise.resolve(); } }); /** Add TestBed providers, compile, and create DashboardComponent */ function compileAndCreate() { beforeEach(async () => { // #docregion router-harness TestBed.configureTestingModule( Object.assign({}, appConfig, { imports: [DashboardComponent], providers: [ provideRouter([{path: '**', component: DashboardComponent}]), provideHttpClient(), provideHttpClientTesting(), HeroService, ], }), ); harness = await RouterTestingHarness.create(); comp = await harness.navigateByUrl('/', DashboardComponent); TestBed.inject(HttpTestingController).expectOne('api/heroes').flush(getTestHeroes()); // #enddocregion router-harness }); } /** * The (almost) same tests for both. * Only change: the way that the first hero is clicked */ function tests(heroClick: () => Promise<unknown>) { describe('after get dashboard heroes', () => { let router: Router; // Trigger component so it gets heroes and binds to them beforeEach(waitForAsync(() => { router = TestBed.inject(Router); harness.detectChanges(); // runs ngOnInit -> getHeroes })); it('should HAVE heroes', () => { expect(comp.heroes.length) .withContext('should have heroes after service promise resolves') .toBeGreaterThan(0); }); it('should DISPLAY heroes', () => { // Find and examine the displayed heroes // Look for them in the DOM by css class const heroes = harness.routeNativeElement!.querySelectorAll('dashboard-hero'); expect(heroes.length).withContext('should display 4 heroes').toBe(4); }); // #docregion navigate-test it('should tell navigate when hero clicked', async () => { await heroClick(); // trigger click on first inner <div class="hero"> // expecting to navigate to id of the component's first hero const id = comp.heroes[0].id; expect(TestBed.inject(Router).url) .withContext('should nav to HeroDetail for first hero') .toEqual(`/heroes/${id}`); }); // #enddocregion navigate-test }); }
{ "end_byte": 4176, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/dashboard/dashboard.component.spec.ts" }
angular/adev/src/content/examples/testing/src/app/dashboard/dashboard.component.css_0_468
[class*='col-'] { float: left; } *, *::after, *::before { box-sizing: border-box; } h3 { text-align: center; margin-bottom: 0; } [class*='col-'] { padding-right: 20px; padding-bottom: 20px; } [class*='col-']:last-of-type { padding-right: 0; } .grid { margin: 0; } .col-1-4 { width: 25%; } .grid-pad { padding: 10px 0; } .grid-pad > [class*='col-']:last-of-type { padding-right: 20px; } @media (max-width: 1024px) { .grid { margin: 0; } }
{ "end_byte": 468, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/dashboard/dashboard.component.css" }
angular/adev/src/content/examples/testing/src/app/dashboard/dashboard.component.html_0_314
<h2 highlight>{{ title }}</h2> <div class="grid grid-pad"> <!-- #docregion dashboard-hero --> @for (hero of heroes; track hero) { <dashboard-hero class="col-1-4" [hero]="hero" (selected)="gotoDetail($event)" > </dashboard-hero> } <!-- #enddocregion dashboard-hero --> </div>
{ "end_byte": 314, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/dashboard/dashboard.component.html" }
angular/adev/src/content/examples/testing/src/app/dashboard/dashboard-hero.component.css_0_428
.hero { padding: 20px; position: relative; text-align: center; color: #eee; max-height: 120px; width: 100%; min-width: 120px; background-color: #607d8b; border-radius: 2px; } .hero:hover { background-color: #eee; cursor: pointer; color: #607d8b; } @media (max-width: 600px) { .hero { font-size: 10px; max-height: 75px; } } @media (max-width: 1024px) { .hero { min-width: 60px; } }
{ "end_byte": 428, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/dashboard/dashboard-hero.component.css" }
angular/adev/src/content/examples/testing/src/app/dashboard/dashboard-hero.component.spec.ts_0_4957
// #docplaster import {DebugElement} from '@angular/core'; import {ComponentFixture, TestBed, waitForAsync} from '@angular/core/testing'; import {By} from '@angular/platform-browser'; import {first} from 'rxjs/operators'; import {addMatchers, click} from '../../testing'; import {appProviders} from '../app.config'; import {Hero} from '../model/hero'; import {DashboardHeroComponent} from './dashboard-hero.component'; beforeEach(addMatchers); describe('DashboardHeroComponent when tested directly', () => { let comp: DashboardHeroComponent; let expectedHero: Hero; let fixture: ComponentFixture<DashboardHeroComponent>; let heroDe: DebugElement; let heroEl: HTMLElement; beforeEach(() => { // #docregion setup, config-testbed TestBed.configureTestingModule({ providers: appProviders, }); // #enddocregion setup, config-testbed }); beforeEach(async () => { // #docregion setup fixture = TestBed.createComponent(DashboardHeroComponent); fixture.autoDetectChanges(); comp = fixture.componentInstance; // find the hero's DebugElement and element heroDe = fixture.debugElement.query(By.css('.hero')); heroEl = heroDe.nativeElement; // mock the hero supplied by the parent component expectedHero = {id: 42, name: 'Test Name'}; // simulate the parent setting the input property with that hero fixture.componentRef.setInput('hero', expectedHero); // wait for initial data binding await fixture.whenStable(); // #enddocregion setup }); // #docregion name-test it('should display hero name in uppercase', () => { const expectedPipedName = expectedHero.name.toUpperCase(); expect(heroEl.textContent).toContain(expectedPipedName); }); // #enddocregion name-test // #docregion click-test it('should raise selected event when clicked (triggerEventHandler)', () => { let selectedHero: Hero | undefined; comp.selected.subscribe((hero: Hero) => (selectedHero = hero)); // #docregion trigger-event-handler heroDe.triggerEventHandler('click'); // #enddocregion trigger-event-handler expect(selectedHero).toBe(expectedHero); }); // #enddocregion click-test // #docregion click-test-2 it('should raise selected event when clicked (element.click)', () => { let selectedHero: Hero | undefined; comp.selected.subscribe((hero: Hero) => (selectedHero = hero)); heroEl.click(); expect(selectedHero).toBe(expectedHero); }); // #enddocregion click-test-2 // #docregion click-test-3 it('should raise selected event when clicked (click helper with DebugElement)', () => { let selectedHero: Hero | undefined; comp.selected.subscribe((hero: Hero) => (selectedHero = hero)); click(heroDe); // click helper with DebugElement expect(selectedHero).toBe(expectedHero); }); // #enddocregion click-test-3 it('should raise selected event when clicked (click helper with native element)', () => { let selectedHero: Hero | undefined; comp.selected.subscribe((hero: Hero) => (selectedHero = hero)); click(heroEl); // click helper with native element expect(selectedHero).toBe(expectedHero); }); }); ////////////////// describe('DashboardHeroComponent when inside a test host', () => { let testHost: TestHostComponent; let fixture: ComponentFixture<TestHostComponent>; let heroEl: HTMLElement; beforeEach(waitForAsync(() => { // #docregion test-host-setup TestBed.configureTestingModule({ providers: appProviders, imports: [DashboardHeroComponent, TestHostComponent], }) // #enddocregion test-host-setup .compileComponents(); })); beforeEach(() => { // #docregion test-host-setup // create TestHostComponent instead of DashboardHeroComponent fixture = TestBed.createComponent(TestHostComponent); testHost = fixture.componentInstance; heroEl = fixture.nativeElement.querySelector('.hero'); fixture.detectChanges(); // trigger initial data binding // #enddocregion test-host-setup }); // #docregion test-host-tests it('should display hero name', () => { const expectedPipedName = testHost.hero.name.toUpperCase(); expect(heroEl.textContent).toContain(expectedPipedName); }); it('should raise selected event when clicked', () => { click(heroEl); // selected hero should be the same data bound hero expect(testHost.selectedHero).toBe(testHost.hero); }); // #enddocregion test-host-tests }); ////// Test Host Component ////// import {Component} from '@angular/core'; // #docregion test-host @Component({ standalone: true, imports: [DashboardHeroComponent], template: ` <dashboard-hero [hero]="hero" (selected)="onSelected($event)"> </dashboard-hero>`, }) class TestHostComponent { hero: Hero = {id: 42, name: 'Test Name'}; selectedHero: Hero | undefined; onSelected(hero: Hero) { this.selectedHero = hero; } } // #enddocregion test-host
{ "end_byte": 4957, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/dashboard/dashboard-hero.component.spec.ts" }
angular/adev/src/content/examples/testing/src/app/dashboard/dashboard-hero.component.ts_0_658
// #docregion import {Component, input, output} from '@angular/core'; import {UpperCasePipe} from '@angular/common'; import {Hero} from '../model/hero'; // #docregion component @Component({ standalone: true, selector: 'dashboard-hero', template: ` <button type="button" (click)="click()" class="hero"> {{ hero().name | uppercase }} </button> `, styleUrls: ['./dashboard-hero.component.css'], imports: [UpperCasePipe], }) // #docregion class export class DashboardHeroComponent { hero = input.required<Hero>(); selected = output<Hero>(); click() { this.selected.emit(this.hero()); } } // #enddocregion component, class
{ "end_byte": 658, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/dashboard/dashboard-hero.component.ts" }
angular/adev/src/content/examples/testing/src/app/dashboard/dashboard.component.ts_0_1142
// #docregion import {Component, OnInit} from '@angular/core'; import {Router} from '@angular/router'; import {Hero} from '../model/hero'; import {HeroService} from '../model/hero.service'; import {sharedImports} from '../shared/shared'; import {DashboardHeroComponent} from './dashboard-hero.component'; @Component({ standalone: true, selector: 'app-dashboard', templateUrl: './dashboard.component.html', styleUrls: ['./dashboard.component.css'], imports: [DashboardHeroComponent, sharedImports], }) export class DashboardComponent implements OnInit { heroes: Hero[] = []; // #docregion ctor constructor( private router: Router, private heroService: HeroService, ) {} // #enddocregion ctor ngOnInit() { this.heroService.getHeroes().subscribe((heroes) => (this.heroes = heroes.slice(1, 5))); } // #docregion goto-detail gotoDetail(hero: Hero) { const url = `/heroes/${hero.id}`; this.router.navigateByUrl(url); } // #enddocregion goto-detail get title() { const cnt = this.heroes.length; return cnt === 0 ? 'No Heroes' : cnt === 1 ? 'Top Hero' : `Top ${cnt} Heroes`; } }
{ "end_byte": 1142, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/dashboard/dashboard.component.ts" }
angular/adev/src/content/examples/testing/src/app/twain/twain.component.ts_0_1314
// #docregion import {Component, OnInit, signal} from '@angular/core'; import {AsyncPipe} from '@angular/common'; import {sharedImports} from '../shared/shared'; import {Observable, of} from 'rxjs'; import {catchError, startWith} from 'rxjs/operators'; import {TwainService} from './twain.service'; @Component({ standalone: true, selector: 'twain-quote', // #docregion template template: ` <p class="twain"> <i>{{ quote | async }}</i> </p> <button type="button" (click)="getQuote()">Next quote</button> @if (errorMessage()) { <p class="error">{{ errorMessage() }}</p> }`, // #enddocregion template styles: ['.twain { font-style: italic; } .error { color: red; }'], imports: [AsyncPipe, sharedImports], }) export class TwainComponent implements OnInit { errorMessage = signal(''); quote?: Observable<string>; constructor(private twainService: TwainService) {} ngOnInit(): void { this.getQuote(); } // #docregion get-quote getQuote() { this.errorMessage.set(''); this.quote = this.twainService.getQuote().pipe( startWith('...'), catchError((err: any) => { this.errorMessage.set(err.message || err.toString()); return of('...'); // reset message to placeholder }), ); // #enddocregion get-quote } }
{ "end_byte": 1314, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/twain/twain.component.ts" }
angular/adev/src/content/examples/testing/src/app/twain/twain.component.spec.ts_0_6129
// #docplaster import {fakeAsync, ComponentFixture, TestBed, tick, waitForAsync} from '@angular/core/testing'; import {asyncData, asyncError} from '../../testing'; import {Subject, defer, of, throwError} from 'rxjs'; import {last} from 'rxjs/operators'; import {TwainComponent} from './twain.component'; import {TwainService} from './twain.service'; describe('TwainComponent', () => { let component: TwainComponent; let fixture: ComponentFixture<TwainComponent>; let getQuoteSpy: jasmine.Spy; let quoteEl: HTMLElement; let testQuote: string; // Helper function to get the error message element value // An *ngIf keeps it out of the DOM until there is an error const errorMessage = () => { const el = fixture.nativeElement.querySelector('.error'); return el ? el.textContent : null; }; // #docregion setup beforeEach(() => { TestBed.configureTestingModule({ imports: [TwainComponent], providers: [TwainService], }); testQuote = 'Test Quote'; // #docregion spy // Create a fake TwainService object with a `getQuote()` spy const twainService = TestBed.inject(TwainService); // Make the spy return a synchronous Observable with the test data getQuoteSpy = spyOn(twainService, 'getQuote').and.returnValue(of(testQuote)); // #enddocregion spy fixture = TestBed.createComponent(TwainComponent); fixture.autoDetectChanges(); component = fixture.componentInstance; quoteEl = fixture.nativeElement.querySelector('.twain'); }); // #enddocregion setup describe('when test with synchronous observable', () => { it('should not show quote before OnInit', () => { expect(quoteEl.textContent).withContext('nothing displayed').toBe(''); expect(errorMessage()).withContext('should not show error element').toBeNull(); expect(getQuoteSpy.calls.any()).withContext('getQuote not yet called').toBe(false); }); // The quote would not be immediately available if the service were truly async. // #docregion sync-test it('should show quote after component initialized', async () => { await fixture.whenStable(); // onInit() // sync spy result shows testQuote immediately after init expect(quoteEl.textContent).toBe(testQuote); expect(getQuoteSpy.calls.any()).withContext('getQuote called').toBe(true); }); // #enddocregion sync-test // The error would not be immediately available if the service were truly async. // Use `fakeAsync` because the component error calls `setTimeout` // #docregion error-test it('should display error when TwainService fails', fakeAsync(() => { // tell spy to return an error observable after a timeout getQuoteSpy.and.returnValue( defer(() => { return new Promise((resolve, reject) => { setTimeout(() => { reject('TwainService test failure'); }); }); }), ); fixture.detectChanges(); // onInit() // sync spy errors immediately after init tick(); // flush the setTimeout() fixture.detectChanges(); // update errorMessage within setTimeout() expect(errorMessage()) .withContext('should display error') .toMatch(/test failure/); expect(quoteEl.textContent).withContext('should show placeholder').toBe('...'); })); // #enddocregion error-test }); describe('when test with asynchronous observable', () => { beforeEach(() => { // #docregion async-setup // Simulate delayed observable values with the `asyncData()` helper getQuoteSpy.and.returnValue(asyncData(testQuote)); // #enddocregion async-setup }); it('should not show quote before OnInit', () => { expect(quoteEl.textContent).withContext('nothing displayed').toBe(''); expect(errorMessage()).withContext('should not show error element').toBeNull(); expect(getQuoteSpy.calls.any()).withContext('getQuote not yet called').toBe(false); }); it('should still not show quote after component initialized', () => { fixture.detectChanges(); // getQuote service is async => still has not returned with quote // so should show the start value, '...' expect(quoteEl.textContent).withContext('should show placeholder').toBe('...'); expect(errorMessage()).withContext('should not show error').toBeNull(); expect(getQuoteSpy.calls.any()).withContext('getQuote called').toBe(true); }); // #docregion fake-async-test it('should show quote after getQuote (fakeAsync)', fakeAsync(() => { fixture.detectChanges(); // ngOnInit() expect(quoteEl.textContent).withContext('should show placeholder').toBe('...'); tick(); // flush the observable to get the quote fixture.detectChanges(); // update view expect(quoteEl.textContent).withContext('should show quote').toBe(testQuote); expect(errorMessage()).withContext('should not show error').toBeNull(); })); // #enddocregion fake-async-test // #docregion async-test it('should show quote after getQuote (async)', async () => { fixture.detectChanges(); // ngOnInit() expect(quoteEl.textContent).withContext('should show placeholder').toBe('...'); await fixture.whenStable(); // wait for async getQuote fixture.detectChanges(); // update view with quote expect(quoteEl.textContent).toBe(testQuote); expect(errorMessage()).withContext('should not show error').toBeNull(); }); // #enddocregion async-test it('should display error when TwainService fails', fakeAsync(() => { // tell spy to return an async error observable getQuoteSpy.and.returnValue(asyncError<string>('TwainService test failure')); fixture.detectChanges(); tick(); // component shows error after a setTimeout() fixture.detectChanges(); // update error message expect(errorMessage()) .withContext('should display error') .toMatch(/test failure/); expect(quoteEl.textContent).withContext('should show placeholder').toBe('...'); })); }); });
{ "end_byte": 6129, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/twain/twain.component.spec.ts" }
angular/adev/src/content/examples/testing/src/app/twain/twain.component.marbles.spec.ts_0_3116
// #docplaster import {fakeAsync, ComponentFixture, TestBed, tick} from '@angular/core/testing'; // #docregion import-marbles import {cold, getTestScheduler} from 'jasmine-marbles'; // #enddocregion import-marbles import {TwainService} from './twain.service'; import {TwainComponent} from './twain.component'; describe('TwainComponent (marbles)', () => { let component: TwainComponent; let fixture: ComponentFixture<TwainComponent>; let getQuoteSpy: jasmine.Spy; let quoteEl: HTMLElement; let testQuote: string; // Helper function to get the error message element value // An *ngIf keeps it out of the DOM until there is an error const errorMessage = () => { const el = fixture.nativeElement.querySelector('.error'); return el ? el.textContent : null; }; beforeEach(() => { // Create a fake TwainService object with a `getQuote()` spy const twainService = jasmine.createSpyObj('TwainService', ['getQuote']); getQuoteSpy = twainService.getQuote; TestBed.configureTestingModule({ imports: [TwainComponent], providers: [{provide: TwainService, useValue: twainService}], }); fixture = TestBed.createComponent(TwainComponent); component = fixture.componentInstance; quoteEl = fixture.nativeElement.querySelector('.twain'); testQuote = 'Test Quote'; }); // A synchronous test that simulates async behavior // #docregion get-quote-test it('should show quote after getQuote (marbles)', () => { // observable test quote value and complete(), after delay // #docregion test-quote-marbles const q$ = cold('---x|', {x: testQuote}); // #enddocregion test-quote-marbles getQuoteSpy.and.returnValue(q$); fixture.detectChanges(); // ngOnInit() expect(quoteEl.textContent).withContext('should show placeholder').toBe('...'); // #docregion test-scheduler-flush getTestScheduler().flush(); // flush the observables // #enddocregion test-scheduler-flush fixture.detectChanges(); // update view expect(quoteEl.textContent).withContext('should show quote').toBe(testQuote); expect(errorMessage()).withContext('should not show error').toBeNull(); }); // #enddocregion get-quote-test // Still need fakeAsync() because of component's setTimeout() // #docregion error-test it('should display error when TwainService fails', fakeAsync(() => { // observable error after delay // #docregion error-marbles const q$ = cold('---#|', null, new Error('TwainService test failure')); // #enddocregion error-marbles getQuoteSpy.and.returnValue(q$); fixture.detectChanges(); // ngOnInit() expect(quoteEl.textContent).withContext('should show placeholder').toBe('...'); getTestScheduler().flush(); // flush the observables tick(); // component shows error after a setTimeout() fixture.detectChanges(); // update error message expect(errorMessage()) .withContext('should display error') .toMatch(/test failure/); expect(quoteEl.textContent).withContext('should show placeholder').toBe('...'); })); // #enddocregion error-test });
{ "end_byte": 3116, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/twain/twain.component.marbles.spec.ts" }
angular/adev/src/content/examples/testing/src/app/twain/quote.ts_0_58
export interface Quote { id: number; quote: string; }
{ "end_byte": 58, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/twain/quote.ts" }
angular/adev/src/content/examples/testing/src/app/twain/twain.data.ts_0_964
import {Quote} from './quote'; export const QUOTES: Quote[] = [ 'Always do right. This will gratify some people and astonish the rest.', 'I have never let my schooling interfere with my education.', "Don't go around saying the world owes you a living. The world owes you nothing. It was here first.", 'Whenever you find yourself on the side of the majority, it is time to pause and reflect.', "If you tell the truth, you don't have to remember anything.", 'Clothes make the man. Naked people have little or no influence on society.', "It's not the size of the dog in the fight, it's the size of the fight in the dog.", "Truth is stranger than fiction, but it is because Fiction is obliged to stick to possibilities; Truth isn't.", 'The man who does not read good books has no advantage over the man who cannot read them.', 'Get your facts first, and then you can distort them as much as you please.', ].map((q, i) => ({id: i + 1, quote: q}));
{ "end_byte": 964, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/twain/twain.data.ts" }
angular/adev/src/content/examples/testing/src/app/twain/twain.service.ts_0_1608
// Mark Twain Quote service gets quotes from server import {Injectable} from '@angular/core'; import {HttpClient, HttpErrorResponse} from '@angular/common/http'; import {Observable, of, throwError, Observer} from 'rxjs'; import {concat, map, retryWhen, switchMap, take, tap} from 'rxjs/operators'; import {Quote} from './quote'; @Injectable() export class TwainService { constructor(private http: HttpClient) {} private nextId = 1; getQuote(): Observable<string> { return Observable.create((observer: Observer<number>) => observer.next(this.nextId++)).pipe( // tap((id: number) => console.log(id)), // tap((id: number) => { throw new Error('Simulated server error'); }), switchMap((id: number) => this.http.get<Quote>(`api/quotes/${id}`)), // tap((q : Quote) => console.log(q)), map((q: Quote) => q.quote), // `errors` is observable of http.get errors retryWhen((errors) => errors.pipe( switchMap((error: HttpErrorResponse) => { if (error.status === 404) { // Queried for quote that doesn't exist. this.nextId = 1; // retry with quote id:1 return of(null); // signal OK to retry } // Some other HTTP error. console.error(error); return throwError('Cannot get Twain quotes from the server'); }), take(2), // If a second retry value, then didn't find id:1 and triggers the following error concat(throwError('There are no Twain quotes')), // didn't find id:1 ), ), ); } }
{ "end_byte": 1608, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/twain/twain.service.ts" }
angular/adev/src/content/examples/testing/src/app/model/hero.service.spec.ts_0_7244
import {HttpClientTestingModule, HttpTestingController} from '@angular/common/http/testing'; // Other imports import {TestBed} from '@angular/core/testing'; import {HttpClient, HttpResponse, HttpErrorResponse} from '@angular/common/http'; import {asyncData, asyncError} from '../../testing/async-observable-helpers'; import {Hero} from './hero'; import {HeroService} from './hero.service'; describe('HeroesService (with spies)', () => { // #docregion test-with-spies let httpClientSpy: jasmine.SpyObj<HttpClient>; let heroService: HeroService; beforeEach(() => { // TODO: spy on other methods too httpClientSpy = jasmine.createSpyObj('HttpClient', ['get']); heroService = new HeroService(httpClientSpy); }); it('should return expected heroes (HttpClient called once)', (done: DoneFn) => { const expectedHeroes: Hero[] = [ {id: 1, name: 'A'}, {id: 2, name: 'B'}, ]; httpClientSpy.get.and.returnValue(asyncData(expectedHeroes)); heroService.getHeroes().subscribe({ next: (heroes) => { expect(heroes).withContext('expected heroes').toEqual(expectedHeroes); done(); }, error: done.fail, }); expect(httpClientSpy.get.calls.count()).withContext('one call').toBe(1); }); it('should return an error when the server returns a 404', (done: DoneFn) => { const errorResponse = new HttpErrorResponse({ error: 'test 404 error', status: 404, statusText: 'Not Found', }); httpClientSpy.get.and.returnValue(asyncError(errorResponse)); heroService.getHeroes().subscribe({ next: (heroes) => done.fail('expected an error, not heroes'), error: (error) => { expect(error.message).toContain('test 404 error'); done(); }, }); }); // #enddocregion test-with-spies }); describe('HeroesService (with mocks)', () => { let httpClient: HttpClient; let httpTestingController: HttpTestingController; let heroService: HeroService; beforeEach(() => { TestBed.configureTestingModule({ // Import the HttpClient mocking services imports: [HttpClientTestingModule], // Provide the service-under-test providers: [HeroService], }); // Inject the http, test controller, and service-under-test // as they will be referenced by each test. httpClient = TestBed.inject(HttpClient); httpTestingController = TestBed.inject(HttpTestingController); heroService = TestBed.inject(HeroService); }); afterEach(() => { // After every test, assert that there are no more pending requests. httpTestingController.verify(); }); /// HeroService method tests begin /// describe('#getHeroes', () => { let expectedHeroes: Hero[]; beforeEach(() => { heroService = TestBed.inject(HeroService); expectedHeroes = [ {id: 1, name: 'A'}, {id: 2, name: 'B'}, ] as Hero[]; }); it('should return expected heroes (called once)', () => { heroService.getHeroes().subscribe({ next: (heroes) => expect(heroes).withContext('should return expected heroes').toEqual(expectedHeroes), error: fail, }); // HeroService should have made one request to GET heroes from expected URL const req = httpTestingController.expectOne(heroService.heroesUrl); expect(req.request.method).toEqual('GET'); // Respond with the mock heroes req.flush(expectedHeroes); }); it('should be OK returning no heroes', () => { heroService.getHeroes().subscribe({ next: (heroes) => expect(heroes.length).withContext('should have empty heroes array').toEqual(0), error: fail, }); const req = httpTestingController.expectOne(heroService.heroesUrl); req.flush([]); // Respond with no heroes }); it('should turn 404 into a user-friendly error', () => { const msg = 'Deliberate 404'; heroService.getHeroes().subscribe({ next: (heroes) => fail('expected to fail'), error: (error) => expect(error.message).toContain(msg), }); const req = httpTestingController.expectOne(heroService.heroesUrl); // respond with a 404 and the error message in the body req.flush(msg, {status: 404, statusText: 'Not Found'}); }); it('should return expected heroes (called multiple times)', () => { heroService.getHeroes().subscribe(); heroService.getHeroes().subscribe(); heroService.getHeroes().subscribe({ next: (heroes) => expect(heroes).withContext('should return expected heroes').toEqual(expectedHeroes), error: fail, }); const requests = httpTestingController.match(heroService.heroesUrl); expect(requests.length).withContext('calls to getHeroes()').toEqual(3); // Respond to each request with different mock hero results requests[0].flush([]); requests[1].flush([{id: 1, name: 'bob'}]); requests[2].flush(expectedHeroes); }); }); describe('#updateHero', () => { // Expecting the query form of URL so should not 404 when id not found const makeUrl = (id: number) => `${heroService.heroesUrl}/?id=${id}`; it('should update a hero and return it', () => { const updateHero: Hero = {id: 1, name: 'A'}; heroService.updateHero(updateHero).subscribe({ next: (data) => expect(data).withContext('should return the hero').toEqual(updateHero), error: fail, }); // HeroService should have made one request to PUT hero const req = httpTestingController.expectOne(heroService.heroesUrl); expect(req.request.method).toEqual('PUT'); expect(req.request.body).toEqual(updateHero); // Expect server to return the hero after PUT const expectedResponse = new HttpResponse({ status: 200, statusText: 'OK', body: updateHero, }); req.event(expectedResponse); }); it('should turn 404 error into user-facing error', () => { const msg = 'Deliberate 404'; const updateHero: Hero = {id: 1, name: 'A'}; heroService.updateHero(updateHero).subscribe({ next: (heroes) => fail('expected to fail'), error: (error) => expect(error.message).toContain(msg), }); const req = httpTestingController.expectOne(heroService.heroesUrl); // respond with a 404 and the error message in the body req.flush(msg, {status: 404, statusText: 'Not Found'}); }); it('should turn network error into user-facing error', (done) => { // Create mock ProgressEvent with type `error`, raised when something goes wrong at // the network level. Connection timeout, DNS error, offline, etc. const errorEvent = new ProgressEvent('error'); const updateHero: Hero = {id: 1, name: 'A'}; heroService.updateHero(updateHero).subscribe({ next: (heroes) => fail('expected to fail'), error: (error) => { expect(error).toBe(errorEvent); done(); }, }); const req = httpTestingController.expectOne(heroService.heroesUrl); // Respond with mock error req.error(errorEvent); }); }); // TODO: test other HeroService methods });
{ "end_byte": 7244, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/model/hero.service.spec.ts" }
angular/adev/src/content/examples/testing/src/app/model/hero.ts_0_56
export interface Hero { id: number; name: string; }
{ "end_byte": 56, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/model/hero.ts" }
angular/adev/src/content/examples/testing/src/app/model/user.service.ts_0_181
import {Injectable, signal} from '@angular/core'; @Injectable({providedIn: 'root'}) export class UserService { isLoggedIn = signal(true); user = signal({name: 'Sam Spade'}); }
{ "end_byte": 181, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/model/user.service.ts" }
angular/adev/src/content/examples/testing/src/app/model/index.ts_0_88
export * from './hero'; export * from './hero.service'; export * from './user.service';
{ "end_byte": 88, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/model/index.ts" }
angular/adev/src/content/examples/testing/src/app/model/hero.service.ts_0_3276
import {HttpClient, HttpErrorResponse, HttpHeaders} from '@angular/common/http'; import {Injectable} from '@angular/core'; import {Observable} from 'rxjs'; import {catchError, map, tap} from 'rxjs/operators'; import {Hero} from './hero'; const httpOptions = { headers: new HttpHeaders({'Content-Type': 'application/json'}), }; @Injectable({providedIn: 'root'}) export class HeroService { readonly heroesUrl = 'api/heroes'; // URL to web api constructor(private http: HttpClient) {} /** GET heroes from the server */ getHeroes(): Observable<Hero[]> { return this.http.get<Hero[]>(this.heroesUrl).pipe( tap((heroes) => this.log('fetched heroes')), catchError(this.handleError('getHeroes')), ) as Observable<Hero[]>; } /** GET hero by id. Return `undefined` when id not found */ getHero<Data>(id: number | string): Observable<Hero> { if (typeof id === 'string') { id = parseInt(id, 10); } const url = `${this.heroesUrl}/?id=${id}`; return this.http.get<Hero[]>(url).pipe( map((heroes) => heroes[0]), // returns a {0|1} element array tap((h) => { const outcome = h ? 'fetched' : 'did not find'; this.log(`${outcome} hero id=${id}`); }), catchError(this.handleError<Hero>(`getHero id=${id}`)), ); } //////// Save methods ////////// /** POST: add a new hero to the server */ addHero(hero: Hero): Observable<Hero> { return this.http.post<Hero>(this.heroesUrl, hero, httpOptions).pipe( tap((addedHero) => this.log(`added hero w/ id=${addedHero.id}`)), catchError(this.handleError<Hero>('addHero')), ); } /** DELETE: delete the hero from the server */ deleteHero(hero: Hero | number): Observable<Hero> { const id = typeof hero === 'number' ? hero : hero.id; const url = `${this.heroesUrl}/${id}`; return this.http.delete<Hero>(url, httpOptions).pipe( tap((_) => this.log(`deleted hero id=${id}`)), catchError(this.handleError<Hero>('deleteHero')), ); } /** PUT: update the hero on the server */ updateHero(hero: Hero): Observable<any> { return this.http.put(this.heroesUrl, hero, httpOptions).pipe( tap((_) => this.log(`updated hero id=${hero.id}`)), catchError(this.handleError<any>('updateHero')), ); } /** * Returns a function that handles Http operation failures. * This error handler lets the app continue to run as if no error occurred. * * @param operation - name of the operation that failed */ private handleError<T>(operation = 'operation') { return (error: HttpErrorResponse): Observable<T> => { // TODO: send the error to remote logging infrastructure console.error(error); // log to console instead // If a native error is caught, do not transform it. We only want to // transform response errors that are not wrapped in an `Error`. if (error.error instanceof Event) { throw error.error; } const message = `server returned code ${error.status} with body "${error.error}"`; // TODO: better job of transforming error for user consumption throw new Error(`${operation} failed: ${message}`); }; } private log(message: string) { console.log('HeroService: ' + message); } }
{ "end_byte": 3276, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/model/hero.service.ts" }
angular/adev/src/content/examples/testing/src/app/model/testing/http-client.spec.ts_0_5396
// Http testing module and mocking controller import {HttpClientTestingModule, HttpTestingController} from '@angular/common/http/testing'; // Other imports import {TestBed} from '@angular/core/testing'; import {HttpClient, HttpErrorResponse} from '@angular/common/http'; import {HttpHeaders} from '@angular/common/http'; interface Data { name: string; } const testUrl = '/data'; describe('HttpClient testing', () => { let httpClient: HttpClient; let httpTestingController: HttpTestingController; beforeEach(() => { TestBed.configureTestingModule({ imports: [HttpClientTestingModule], }); // Inject the http service and test controller for each test httpClient = TestBed.inject(HttpClient); httpTestingController = TestBed.inject(HttpTestingController); }); afterEach(() => { // After every test, assert that there are no more pending requests. httpTestingController.verify(); }); /// Tests begin /// it('can test HttpClient.get', () => { const testData: Data = {name: 'Test Data'}; // Make an HTTP GET request httpClient.get<Data>(testUrl).subscribe((data) => // When observable resolves, result should match test data expect(data).toEqual(testData), ); // The following `expectOne()` will match the request's URL. // If no requests or multiple requests matched that URL // `expectOne()` would throw. const req = httpTestingController.expectOne('/data'); // Assert that the request is a GET. expect(req.request.method).toEqual('GET'); // Respond with mock data, causing Observable to resolve. // Subscribe callback asserts that correct data was returned. req.flush(testData); // Finally, assert that there are no outstanding requests. httpTestingController.verify(); }); it('can test HttpClient.get with matching header', () => { const testData: Data = {name: 'Test Data'}; // Make an HTTP GET request with specific header httpClient .get<Data>(testUrl, { headers: new HttpHeaders({Authorization: 'my-auth-token'}), }) .subscribe((data) => expect(data).toEqual(testData)); // Find request with a predicate function. // Expect one request with an authorization header const req = httpTestingController.expectOne((request) => request.headers.has('Authorization')); req.flush(testData); }); it('can test multiple requests', () => { const testData: Data[] = [{name: 'bob'}, {name: 'carol'}, {name: 'ted'}, {name: 'alice'}]; // Make three requests in a row httpClient .get<Data[]>(testUrl) .subscribe((d) => expect(d.length).withContext('should have no data').toEqual(0)); httpClient .get<Data[]>(testUrl) .subscribe((d) => expect(d).withContext('should be one element array').toEqual([testData[0]]), ); httpClient .get<Data[]>(testUrl) .subscribe((d) => expect(d).withContext('should be expected data').toEqual(testData)); // get all pending requests that match the given URL const requests = httpTestingController.match(testUrl); expect(requests.length).toEqual(3); // Respond to each request with different results requests[0].flush([]); requests[1].flush([testData[0]]); requests[2].flush(testData); }); it('can test for 404 error', () => { const emsg = 'deliberate 404 error'; httpClient.get<Data[]>(testUrl).subscribe({ next: (data) => fail('should have failed with the 404 error'), error: (error: HttpErrorResponse) => { expect(error.status).withContext('status').toEqual(404); expect(error.error).withContext('message').toEqual(emsg); }, }); const req = httpTestingController.expectOne(testUrl); // Respond with mock error req.flush(emsg, {status: 404, statusText: 'Not Found'}); }); it('can test for network error', (done) => { // Create mock ProgressEvent with type `error`, raised when something goes wrong at // the network level. Connection timeout, DNS error, offline, etc. const errorEvent = new ProgressEvent('error'); httpClient.get<Data[]>(testUrl).subscribe({ next: (data) => fail('should have failed with the network error'), error: (error: HttpErrorResponse) => { expect(error.error).toBe(errorEvent); done(); }, }); const req = httpTestingController.expectOne(testUrl); // Respond with mock error req.error(errorEvent); }); it('httpTestingController.verify should fail if HTTP response not simulated', () => { // Sends request httpClient.get('some/api').subscribe(); // verify() should fail because haven't handled the pending request. expect(() => httpTestingController.verify()).toThrow(); // Now get and flush the request so that afterEach() doesn't fail const req = httpTestingController.expectOne('some/api'); req.flush(null); }); // Proves that verify in afterEach() really would catch error // if test doesn't simulate the HTTP response. // // Must disable this test because can't catch an error in an afterEach(). // Uncomment if you want to confirm that afterEach() does the job. // it('afterEach() should fail when HTTP response not simulated',() => { // // Sends request which is never handled by this test // httpClient.get('some/api').subscribe(); // }); });
{ "end_byte": 5396, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/model/testing/http-client.spec.ts" }
angular/adev/src/content/examples/testing/src/app/model/testing/test-hero.service.ts_0_1759
import {Injectable} from '@angular/core'; import {Observable} from 'rxjs'; import {asyncData} from '../../../testing'; import {map} from 'rxjs/operators'; // re-export for tester convenience export {Hero} from '../hero'; export {HeroService} from '../hero.service'; export {getTestHeroes} from './test-heroes'; import {Hero} from '../hero'; import {HeroService} from '../hero.service'; import {getTestHeroes} from './test-heroes'; @Injectable() /** * FakeHeroService pretends to make real http requests. * implements only as much of HeroService as is actually consumed by the app */ export class TestHeroService extends HeroService { constructor() { // This is a fake testing service that won't be making HTTP // requests so we can pass in `null` as the HTTP client. super(null!); } heroes = getTestHeroes(); lastResult!: Observable<any>; // result from last method call override addHero(hero: Hero): Observable<Hero> { throw new Error('Method not implemented.'); } override deleteHero(hero: number | Hero): Observable<Hero> { throw new Error('Method not implemented.'); } override getHeroes(): Observable<Hero[]> { return (this.lastResult = asyncData(this.heroes)); } override getHero(id: number | string): Observable<Hero> { if (typeof id === 'string') { id = parseInt(id, 10); } const hero = this.heroes.find((h) => h.id === id); this.lastResult = asyncData(hero); return this.lastResult; } override updateHero(hero: Hero): Observable<Hero> { return (this.lastResult = this.getHero(hero.id).pipe( map((h) => { if (h) { return Object.assign(h, hero); } throw new Error(`Hero ${hero.id} not found`); }), )); } }
{ "end_byte": 1759, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/model/testing/test-hero.service.ts" }
angular/adev/src/content/examples/testing/src/app/model/testing/index.ts_0_37
export * from './test-hero.service';
{ "end_byte": 37, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/model/testing/index.ts" }
angular/adev/src/content/examples/testing/src/app/model/testing/test-heroes.ts_0_306
import {Hero} from '../hero'; /** return fresh array of test heroes */ export function getTestHeroes(): Hero[] { return [ {id: 41, name: 'Bob'}, {id: 42, name: 'Carol'}, {id: 43, name: 'Ted'}, {id: 44, name: 'Alice'}, {id: 45, name: 'Speedy'}, {id: 46, name: 'Stealthy'}, ]; }
{ "end_byte": 306, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/model/testing/test-heroes.ts" }
angular/adev/src/content/examples/testing/src/app/hero/hero-list.component.spec.ts_0_4782
import {ComponentFixture, fakeAsync, TestBed, tick, waitForAsync} from '@angular/core/testing'; import {By} from '@angular/platform-browser'; import {DebugElement} from '@angular/core'; import {Router} from '@angular/router'; import {addMatchers} from '../../testing'; import {HeroService} from '../model/hero.service'; import {getTestHeroes, TestHeroService} from '../model/testing/test-hero.service'; import {HeroListComponent} from './hero-list.component'; import {HighlightDirective} from '../shared/highlight.directive'; import {appConfig} from '../app.config'; const HEROES = getTestHeroes(); let comp: HeroListComponent; let fixture: ComponentFixture<HeroListComponent>; let page: Page; /////// Tests ////// describe('HeroListComponent', () => { beforeEach(waitForAsync(() => { addMatchers(); const routerSpy = jasmine.createSpyObj('Router', ['navigate']); TestBed.configureTestingModule( Object.assign({}, appConfig, { providers: [ {provide: HeroService, useClass: TestHeroService}, {provide: Router, useValue: routerSpy}, ], }), ) .compileComponents() .then(createComponent); })); it('should display heroes', () => { expect(page.heroRows.length).toBeGreaterThan(0); }); it('1st hero should match 1st test hero', () => { const expectedHero = HEROES[0]; const actualHero = page.heroRows[0].textContent; expect(actualHero).withContext('hero.id').toContain(expectedHero.id.toString()); expect(actualHero).withContext('hero.name').toContain(expectedHero.name); }); it('should select hero on click', fakeAsync(() => { const expectedHero = HEROES[1]; const btn = page.heroRows[1].querySelector('button'); btn!.dispatchEvent(new Event('click')); tick(); // `.toEqual` because selectedHero is clone of expectedHero; see FakeHeroService expect(comp.selectedHero).toEqual(expectedHero); })); it('should navigate to selected hero detail on click', fakeAsync(() => { const expectedHero = HEROES[1]; const btn = page.heroRows[1].querySelector('button'); btn!.dispatchEvent(new Event('click')); tick(); // should have navigated expect(page.navSpy.calls.any()).withContext('navigate called').toBe(true); // composed hero detail will be URL like 'heroes/42' // expect link array with the route path and hero id // first argument to router.navigate is link array const navArgs = page.navSpy.calls.first().args[0]; expect(navArgs[0]).withContext('nav to heroes detail URL').toContain('heroes'); expect(navArgs[1]).withContext('expected hero.id').toBe(expectedHero.id); })); it('should find `HighlightDirective` with `By.directive', () => { // #docregion by // Can find DebugElement either by css selector or by directive const h2 = fixture.debugElement.query(By.css('h2')); const directive = fixture.debugElement.query(By.directive(HighlightDirective)); // #enddocregion by expect(h2).toBe(directive); }); it('should color header with `HighlightDirective`', () => { const h2 = page.highlightDe.nativeElement as HTMLElement; const bgColor = h2.style.backgroundColor; // different browsers report color values differently const isExpectedColor = bgColor === 'gold' || bgColor === 'rgb(255, 215, 0)'; expect(isExpectedColor).withContext('backgroundColor').toBe(true); }); it("the `HighlightDirective` is among the element's providers", () => { expect(page.highlightDe.providerTokens) .withContext('HighlightDirective') .toContain(HighlightDirective); }); }); /////////// Helpers ///// /** Create the component and set the `page` test variables */ function createComponent() { fixture = TestBed.createComponent(HeroListComponent); comp = fixture.componentInstance; // change detection triggers ngOnInit which gets a hero fixture.detectChanges(); return fixture.whenStable().then(() => { // got the heroes and updated component // change detection updates the view fixture.detectChanges(); page = new Page(); }); } class Page { /** Hero line elements */ heroRows: HTMLLIElement[]; /** Highlighted DebugElement */ highlightDe: DebugElement; /** Spy on router navigate method */ navSpy: jasmine.Spy; constructor() { const heroRowNodes = fixture.nativeElement.querySelectorAll('li'); this.heroRows = Array.from(heroRowNodes); // Find the first element with an attached HighlightDirective this.highlightDe = fixture.debugElement.query(By.directive(HighlightDirective)); // Get the component's injected router navigation spy const routerSpy = fixture.debugElement.injector.get(Router); this.navSpy = routerSpy.navigate as jasmine.Spy; } }
{ "end_byte": 4782, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/hero/hero-list.component.spec.ts" }
angular/adev/src/content/examples/testing/src/app/hero/hero-list.component.css_0_1060
.selected { background-color: #cfd8dc !important; color: white; } .heroes { margin: 0 0 2em 0; list-style-type: none; padding: 0; width: 15em; } .heroes li { display: flex; } .heroes button { flex: 1; cursor: pointer; position: relative; left: 0; background-color: #eee; margin: 0.5em; padding: 0; border-radius: 4px; display: flex; align-items: stretch; height: 1.8em; } .heroes button:hover { color: #2c3a41; background-color: #e6e6e6; left: 0.1em; } .heroes button:active { background-color: #525252; color: #fafafa; } .heroes button.selected { background-color: black; color: white; } .heroes button.selected:hover { background-color: #505050; color: white; } .heroes button.selected:active { background-color: black; color: white; } .heroes .badge { display: inline-block; font-size: small; color: white; padding: 0.8em 0.7em 0 0.7em; background-color: #405061; line-height: 1em; margin-right: 0.8em; border-radius: 4px 0 0 4px; } .heroes .name { align-self: center; }
{ "end_byte": 1060, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/hero/hero-list.component.css" }
angular/adev/src/content/examples/testing/src/app/hero/hero-detail.component.ts_0_1665
// #docplaster import {Component, OnInit} from '@angular/core'; import {ActivatedRoute, Router, RouterLink} from '@angular/router'; import {Hero} from '../model/hero'; import {sharedImports} from '../shared/shared'; import {HeroDetailService} from './hero-detail.service'; // #docregion prototype @Component({ standalone: true, selector: 'app-hero-detail', templateUrl: './hero-detail.component.html', styleUrls: ['./hero-detail.component.css'], providers: [HeroDetailService], imports: [sharedImports, RouterLink], }) export class HeroDetailComponent implements OnInit { // #docregion ctor constructor( private heroDetailService: HeroDetailService, private route: ActivatedRoute, private router: Router, ) {} // #enddocregion ctor // #enddocregion prototype hero!: Hero; // #docregion ng-on-init ngOnInit(): void { // get hero when `id` param changes this.route.paramMap.subscribe((pmap) => this.getHero(pmap.get('id'))); } // #enddocregion ng-on-init private getHero(id: string | null): void { // when no id or id===0, create new blank hero if (!id) { this.hero = {id: 0, name: ''} as Hero; return; } this.heroDetailService.getHero(id).subscribe((hero) => { if (hero) { this.hero = hero; } else { this.gotoList(); // id not found; navigate to list } }); } save(): void { this.heroDetailService.saveHero(this.hero).subscribe(() => this.gotoList()); } cancel() { this.gotoList(); } gotoList() { this.router.navigate(['../'], {relativeTo: this.route}); } // #docregion prototype } // #enddocregion prototype
{ "end_byte": 1665, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/hero/hero-detail.component.ts" }
angular/adev/src/content/examples/testing/src/app/hero/hero-detail.component.css_0_465
label { display: inline-block; width: 3em; margin: 0.5em 0; color: #607d8b; font-weight: bold; } input { height: 2em; font-size: 1em; padding-left: 0.4em; } button { margin-top: 20px; font-family: Arial, sans-serif; background-color: #eee; border: none; padding: 5px 10px; border-radius: 4px; cursor: pointer; } button:hover { background-color: #cfd8dc; } button:disabled { background-color: #eee; color: #ccc; cursor: auto; }
{ "end_byte": 465, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/hero/hero-detail.component.css" }
angular/adev/src/content/examples/testing/src/app/hero/hero-detail.service.ts_0_818
import {Injectable} from '@angular/core'; import {Observable} from 'rxjs'; import {map} from 'rxjs/operators'; import {Hero} from '../model/hero'; import {HeroService} from '../model/hero.service'; // #docregion prototype @Injectable({providedIn: 'root'}) export class HeroDetailService { constructor(private heroService: HeroService) {} // #enddocregion prototype // Returns a clone which caller may modify safely getHero(id: number | string): Observable<Hero | null> { if (typeof id === 'string') { id = parseInt(id, 10); } return this.heroService.getHero(id).pipe( map((hero) => (hero ? Object.assign({}, hero) : null)), // clone or null ); } saveHero(hero: Hero) { return this.heroService.updateHero(hero); } // #docregion prototype } // #enddocregion prototype
{ "end_byte": 818, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/hero/hero-detail.service.ts" }
angular/adev/src/content/examples/testing/src/app/hero/hero.routes.ts_0_282
import {HeroListComponent} from './hero-list.component'; import {HeroDetailComponent} from './hero-detail.component'; import {Routes} from '@angular/router'; export default [ {path: '', component: HeroListComponent}, {path: ':id', component: HeroDetailComponent}, ] as Routes;
{ "end_byte": 282, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/hero/hero.routes.ts" }
angular/adev/src/content/examples/testing/src/app/hero/hero-detail.component.spec.ts_0_8907
// #docplaster import {HttpClient, HttpHandler, provideHttpClient} from '@angular/common/http'; import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing'; import {fakeAsync, TestBed, tick} from '@angular/core/testing'; import {provideRouter, Router} from '@angular/router'; import {RouterTestingHarness} from '@angular/router/testing'; import {asyncData, click} from '../../testing'; import {Hero} from '../model/hero'; import {sharedImports} from '../shared/shared'; import {HeroDetailComponent} from './hero-detail.component'; import {HeroDetailService} from './hero-detail.service'; import {HeroListComponent} from './hero-list.component'; ////// Testing Vars ////// let component: HeroDetailComponent; let harness: RouterTestingHarness; let page: Page; ////// Tests ////// describe('HeroDetailComponent', () => { describe('with HeroModule setup', heroModuleSetup); describe('when override its provided HeroDetailService', overrideSetup); describe('with FormsModule setup', formsModuleSetup); describe('with SharedModule setup', sharedModuleSetup); }); /////////////////// const testHero = getTestHeroes()[0]; function overrideSetup() { // #docregion hds-spy class HeroDetailServiceSpy { testHero: Hero = {...testHero}; /* emit cloned test hero */ getHero = jasmine .createSpy('getHero') .and.callFake(() => asyncData(Object.assign({}, this.testHero))); /* emit clone of test hero, with changes merged in */ saveHero = jasmine .createSpy('saveHero') .and.callFake((hero: Hero) => asyncData(Object.assign(this.testHero, hero))); } // #enddocregion hds-spy // #docregion setup-override beforeEach(async () => { await TestBed.configureTestingModule( Object.assign({}, appConfig, { imports: [HeroDetailComponent, HeroListComponent], providers: [ provideRouter([ {path: 'heroes', component: HeroListComponent}, {path: 'heroes/:id', component: HeroDetailComponent}, ]), HttpClient, HttpHandler, // HeroDetailService at this level is IRRELEVANT! {provide: HeroDetailService, useValue: {}}, ], }), ) // #docregion override-component-method .overrideComponent(HeroDetailComponent, { set: {providers: [{provide: HeroDetailService, useClass: HeroDetailServiceSpy}]}, }) // #enddocregion override-component-method .compileComponents(); }); // #enddocregion setup-override // #docregion override-tests let hdsSpy: HeroDetailServiceSpy; beforeEach(async () => { harness = await RouterTestingHarness.create(); component = await harness.navigateByUrl(`/heroes/${testHero.id}`, HeroDetailComponent); page = new Page(); // get the component's injected HeroDetailServiceSpy hdsSpy = harness.routeDebugElement!.injector.get(HeroDetailService) as any; harness.detectChanges(); }); it('should have called `getHero`', () => { expect(hdsSpy.getHero.calls.count()) .withContext('getHero called once') .toBe(1, 'getHero called once'); }); it("should display stub hero's name", () => { expect(page.nameDisplay.textContent).toBe(hdsSpy.testHero.name); }); it('should save stub hero change', fakeAsync(() => { const origName = hdsSpy.testHero.name; const newName = 'New Name'; page.nameInput.value = newName; page.nameInput.dispatchEvent(new Event('input')); // tell Angular expect(component.hero.name).withContext('component hero has new name').toBe(newName); expect(hdsSpy.testHero.name).withContext('service hero unchanged before save').toBe(origName); click(page.saveBtn); expect(hdsSpy.saveHero.calls.count()).withContext('saveHero called once').toBe(1); tick(); // wait for async save to complete expect(hdsSpy.testHero.name).withContext('service hero has new name after save').toBe(newName); expect(TestBed.inject(Router).url).toEqual('/heroes'); })); } // #enddocregion override-tests //////////////////// import {getTestHeroes} from '../model/testing/test-hero.service'; const firstHero = getTestHeroes()[0]; function heroModuleSetup() { // #docregion setup-hero-module beforeEach(async () => { await TestBed.configureTestingModule( Object.assign({}, appConfig, { imports: [HeroDetailComponent, HeroListComponent], providers: [ provideRouter([ {path: 'heroes/:id', component: HeroDetailComponent}, {path: 'heroes', component: HeroListComponent}, ]), provideHttpClient(), provideHttpClientTesting(), ], }), ).compileComponents(); }); // #enddocregion setup-hero-module // #docregion route-good-id describe('when navigate to existing hero', () => { let expectedHero: Hero; beforeEach(async () => { expectedHero = firstHero; await createComponent(expectedHero.id); }); // #docregion selected-tests it("should display that hero's name", () => { expect(page.nameDisplay.textContent).toBe(expectedHero.name); }); // #enddocregion route-good-id it('should navigate when click cancel', () => { click(page.cancelBtn); expect(TestBed.inject(Router).url).toEqual(`/heroes/${expectedHero.id}`); }); it('should save when click save but not navigate immediately', () => { click(page.saveBtn); expect(TestBed.inject(HttpTestingController).expectOne({method: 'PUT', url: 'api/heroes'})); expect(TestBed.inject(Router).url).toEqual('/heroes/41'); }); it('should navigate when click save and save resolves', fakeAsync(() => { click(page.saveBtn); tick(); // wait for async save to complete expect(TestBed.inject(Router).url).toEqual('/heroes/41'); })); // #docregion title-case-pipe it('should convert hero name to Title Case', async () => { harness.fixture.autoDetectChanges(); // get the name's input and display elements from the DOM const hostElement: HTMLElement = harness.routeNativeElement!; const nameInput: HTMLInputElement = hostElement.querySelector('input')!; const nameDisplay: HTMLElement = hostElement.querySelector('span')!; // simulate user entering a new name into the input box nameInput.value = 'quick BROWN fOx'; // Dispatch a DOM event so that Angular learns of input value change. nameInput.dispatchEvent(new Event('input')); // Wait for Angular to update the display binding through the title pipe await harness.fixture.whenStable(); expect(nameDisplay.textContent).toBe('Quick Brown Fox'); }); // #enddocregion selected-tests // #enddocregion title-case-pipe }); // #docregion route-bad-id describe('when navigate to non-existent hero id', () => { beforeEach(async () => { await createComponent(999); }); it('should try to navigate back to hero list', () => { expect(TestBed.inject(Router).url).toEqual('/heroes'); }); }); // #enddocregion route-bad-id } ///////////////////// import {FormsModule} from '@angular/forms'; import {TitleCasePipe} from '../shared/title-case.pipe'; import {appConfig} from '../app.config'; function formsModuleSetup() { // #docregion setup-forms-module beforeEach(async () => { await TestBed.configureTestingModule( Object.assign({}, appConfig, { imports: [FormsModule, HeroDetailComponent, TitleCasePipe], providers: [ provideHttpClient(), provideHttpClientTesting(), provideRouter([{path: 'heroes/:id', component: HeroDetailComponent}]), ], }), ).compileComponents(); }); // #enddocregion setup-forms-module it("should display 1st hero's name", async () => { const expectedHero = firstHero; await createComponent(expectedHero.id).then(() => { expect(page.nameDisplay.textContent).toBe(expectedHero.name); }); }); } /////////////////////// function sharedModuleSetup() { // #docregion setup-shared-module beforeEach(async () => { await TestBed.configureTestingModule( Object.assign({}, appConfig, { imports: [HeroDetailComponent, sharedImports], providers: [ provideRouter([{path: 'heroes/:id', component: HeroDetailComponent}]), provideHttpClient(), provideHttpClientTesting(), ], }), ).compileComponents(); }); // #enddocregion setup-shared-module it("should display 1st hero's name", async () => { const expectedHero = firstHero; await createComponent(expectedHero.id).then(() => { expect(page.nameDisplay.textContent).toBe(expectedHero.name); }); }); } /////////// Helpers ///// /** Create the HeroDetailComponent, initialize it, set test variables */ // #docregion create-component
{ "end_byte": 8907, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/hero/hero-detail.component.spec.ts" }
angular/adev/src/content/examples/testing/src/app/hero/hero-detail.component.spec.ts_8908_10075
async function createComponent(id: number) { harness = await RouterTestingHarness.create(); component = await harness.navigateByUrl(`/heroes/${id}`, HeroDetailComponent); page = new Page(); const request = TestBed.inject(HttpTestingController).expectOne(`api/heroes/?id=${id}`); const hero = getTestHeroes().find((h) => h.id === Number(id)); request.flush(hero ? [hero] : []); harness.detectChanges(); } // #enddocregion create-component // #docregion page class Page { // getter properties wait to query the DOM until called. get buttons() { return this.queryAll<HTMLButtonElement>('button'); } get saveBtn() { return this.buttons[0]; } get cancelBtn() { return this.buttons[1]; } get nameDisplay() { return this.query<HTMLElement>('span'); } get nameInput() { return this.query<HTMLInputElement>('input'); } //// query helpers //// private query<T>(selector: string): T { return harness.routeNativeElement!.querySelector(selector)! as T; } private queryAll<T>(selector: string): T[] { return harness.routeNativeElement!.querySelectorAll(selector) as any as T[]; } } // #enddocregion page
{ "end_byte": 10075, "start_byte": 8908, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/hero/hero-detail.component.spec.ts" }
angular/adev/src/content/examples/testing/src/app/hero/hero-detail.component.html_0_419
<!-- #docregion --> @if (hero) { <div> <h2> <span>{{ hero.name | titlecase }}</span> Details </h2> <div><span>id: </span>{{ hero.id }}</div> <div> <label for="name">name: </label> <input id="name" [(ngModel)]="hero.name" placeholder="name" /> </div> <button type="button" (click)="save()">Save</button> <button type="button" (click)="cancel()">Cancel</button> </div> }
{ "end_byte": 419, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/hero/hero-detail.component.html" }
angular/adev/src/content/examples/testing/src/app/hero/hero-list.component.ts_0_836
import {Component} from '@angular/core'; import {AsyncPipe} from '@angular/common'; import {Router} from '@angular/router'; import {Observable} from 'rxjs'; import {Hero} from '../model/hero'; import {HeroService} from '../model/hero.service'; import {sharedImports} from '../shared/shared'; @Component({ standalone: true, selector: 'app-heroes', templateUrl: './hero-list.component.html', styleUrls: ['./hero-list.component.css'], imports: [AsyncPipe, sharedImports], }) export class HeroListComponent { heroes: Observable<Hero[]>; selectedHero!: Hero; constructor( private router: Router, private heroService: HeroService, ) { this.heroes = this.heroService.getHeroes(); } onSelect(hero: Hero) { this.selectedHero = hero; this.router.navigate(['../heroes', this.selectedHero.id]); } }
{ "end_byte": 836, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/hero/hero-list.component.ts" }
angular/adev/src/content/examples/testing/src/app/hero/hero-list.component.html_0_341
<h2 highlight="gold">My Heroes</h2> <ul class="heroes"> @for (hero of heroes | async; track hero) { <li> <button [class.selected]="hero === selectedHero" type="button" (click)="onSelect(hero)"> <span class="badge">{{ hero.id }}</span> <span class="name">{{ hero.name }}</span> </button> </li> } </ul>
{ "end_byte": 341, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/hero/hero-list.component.html" }
angular/adev/src/content/examples/testing/src/app/banner/banner.component.detect-changes.spec.ts_0_1658
// #docplaster // #docregion // #docregion import-ComponentFixtureAutoDetect import {ComponentFixtureAutoDetect} from '@angular/core/testing'; // #enddocregion import-ComponentFixtureAutoDetect import {ComponentFixture, TestBed} from '@angular/core/testing'; import {BannerComponent} from './banner.component'; describe('BannerComponent (AutoChangeDetect)', () => { let comp: BannerComponent; let fixture: ComponentFixture<BannerComponent>; let h1: HTMLElement; beforeEach(() => { // #docregion auto-detect TestBed.configureTestingModule({ providers: [{provide: ComponentFixtureAutoDetect, useValue: true}], }); // #enddocregion auto-detect fixture = TestBed.createComponent(BannerComponent); comp = fixture.componentInstance; h1 = fixture.nativeElement.querySelector('h1'); }); // #docregion auto-detect-tests it('should display original title', () => { // Hooray! No `fixture.detectChanges()` needed expect(h1.textContent).toContain(comp.title); }); it('should still see original title after comp.title change', async () => { const oldTitle = comp.title; const newTitle = 'Test Title'; comp.title.set(newTitle); // Displayed title is old because Angular didn't yet run change detection expect(h1.textContent).toContain(oldTitle); await fixture.whenStable(); expect(h1.textContent).toContain(newTitle); }); it('should display updated title after detectChanges', () => { comp.title.set('Test Title'); fixture.detectChanges(); // detect changes explicitly expect(h1.textContent).toContain(comp.title); }); // #enddocregion auto-detect-tests });
{ "end_byte": 1658, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/banner/banner.component.detect-changes.spec.ts" }
angular/adev/src/content/examples/testing/src/app/banner/banner.component.ts_0_324
import {Component, signal} from '@angular/core'; // #docregion component @Component({ standalone: true, selector: 'app-banner', template: '<h1>{{title()}}</h1>', styles: ['h1 { color: green; font-size: 350%}'], }) export class BannerComponent { title = signal('Test Tour of Heroes'); } // #enddocregion component
{ "end_byte": 324, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/banner/banner.component.ts" }
angular/adev/src/content/examples/testing/src/app/banner/banner-initial.component.spec.ts_0_3522
// #docplaster // #docregion import-debug-element import {DebugElement} from '@angular/core'; // #enddocregion import-debug-element // #docregion v1 import {ComponentFixture, TestBed, waitForAsync} from '@angular/core/testing'; // #enddocregion v1 // #docregion import-by import {By} from '@angular/platform-browser'; // #enddocregion import-by import {BannerComponent} from './banner-initial.component'; /* // #docregion v1 import { BannerComponent } from './banner.component'; describe('BannerComponent', () => { // #enddocregion v1 */ describe('BannerComponent (initial CLI generated)', () => { // #docregion v1 let component: BannerComponent; let fixture: ComponentFixture<BannerComponent>; beforeEach(waitForAsync(() => { TestBed.configureTestingModule({imports: [BannerComponent]}).compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(BannerComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeDefined(); }); }); // #enddocregion v1 // #docregion v2 describe('BannerComponent (minimal)', () => { it('should create', () => { // #docregion configureTestingModule TestBed.configureTestingModule({imports: [BannerComponent]}); // #enddocregion configureTestingModule // #docregion createComponent const fixture = TestBed.createComponent(BannerComponent); // #enddocregion createComponent // #docregion componentInstance const component = fixture.componentInstance; expect(component).toBeDefined(); // #enddocregion componentInstance }); }); // #enddocregion v2 // #docregion v3 describe('BannerComponent (with beforeEach)', () => { let component: BannerComponent; let fixture: ComponentFixture<BannerComponent>; beforeEach(() => { TestBed.configureTestingModule({imports: [BannerComponent]}); fixture = TestBed.createComponent(BannerComponent); component = fixture.componentInstance; }); it('should create', () => { expect(component).toBeDefined(); }); // #enddocregion v3 // #docregion v4-test-2 it('should contain "banner works!"', () => { const bannerElement: HTMLElement = fixture.nativeElement; expect(bannerElement.textContent).toContain('banner works!'); }); // #enddocregion v4-test-2 // #docregion v4-test-3 it('should have <p> with "banner works!"', () => { // #docregion nativeElement const bannerElement: HTMLElement = fixture.nativeElement; // #enddocregion nativeElement const p = bannerElement.querySelector('p')!; expect(p.textContent).toEqual('banner works!'); }); // #enddocregion v4-test-3 // #docregion v4-test-4 it('should find the <p> with fixture.debugElement.nativeElement)', () => { // #docregion debugElement-nativeElement const bannerDe: DebugElement = fixture.debugElement; const bannerEl: HTMLElement = bannerDe.nativeElement; // #enddocregion debugElement-nativeElement const p = bannerEl.querySelector('p')!; expect(p.textContent).toEqual('banner works!'); }); // #enddocregion v4-test-4 // #docregion v4-test-5 it('should find the <p> with fixture.debugElement.query(By.css)', () => { const bannerDe: DebugElement = fixture.debugElement; const paragraphDe = bannerDe.query(By.css('p')); const p: HTMLElement = paragraphDe.nativeElement; expect(p.textContent).toEqual('banner works!'); }); // #enddocregion v4-test-5 // #docregion v3 }); // #enddocregion v3
{ "end_byte": 3522, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/banner/banner-initial.component.spec.ts" }
angular/adev/src/content/examples/testing/src/app/banner/banner-external.component.ts_0_349
// #docplaster // #docregion import {Component} from '@angular/core'; // #docregion metadata @Component({ standalone: true, selector: 'app-banner', templateUrl: './banner-external.component.html', styleUrls: ['./banner-external.component.css'], }) // #enddocregion metadata export class BannerComponent { title = 'Test Tour of Heroes'; }
{ "end_byte": 349, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/banner/banner-external.component.ts" }
angular/adev/src/content/examples/testing/src/app/banner/banner.component.spec.ts_0_1605
// #docplaster // #docregion import {ComponentFixture, TestBed} from '@angular/core/testing'; import {BannerComponent} from './banner.component'; describe('BannerComponent (inline template)', () => { // #docregion setup let component: BannerComponent; let fixture: ComponentFixture<BannerComponent>; let h1: HTMLElement; beforeEach(() => { TestBed.configureTestingModule({ imports: [BannerComponent], }); fixture = TestBed.createComponent(BannerComponent); component = fixture.componentInstance; // BannerComponent test instance h1 = fixture.nativeElement.querySelector('h1'); }); // #enddocregion setup // #docregion test-w-o-detect-changes it('no title in the DOM after createComponent()', () => { expect(h1.textContent).toEqual(''); }); // #enddocregion test-w-o-detect-changes // #docregion expect-h1-default-v1 it('should display original title', () => { // #enddocregion expect-h1-default-v1 fixture.detectChanges(); // #docregion expect-h1-default-v1 expect(h1.textContent).toContain(component.title); }); // #enddocregion expect-h1-default-v1 // #docregion expect-h1-default it('should display original title after detectChanges()', () => { fixture.detectChanges(); expect(h1.textContent).toContain(component.title); }); // #enddocregion expect-h1-default // #docregion after-change it('should display a different test title', () => { component.title = 'Test Title'; fixture.detectChanges(); expect(h1.textContent).toContain('Test Title'); }); // #enddocregion after-change });
{ "end_byte": 1605, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/banner/banner.component.spec.ts" }
angular/adev/src/content/examples/testing/src/app/banner/banner-external.component.css_0_42
h1 { color: green; font-size: 350%; }
{ "end_byte": 42, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/banner/banner-external.component.css" }
angular/adev/src/content/examples/testing/src/app/banner/banner-initial.component.ts_0_253
// BannerComponent as initially generated by the CLI // #docregion import {Component} from '@angular/core'; @Component({ standalone: true, selector: 'app-banner', template: '<p>banner works!</p>', styles: [], }) export class BannerComponent {}
{ "end_byte": 253, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/banner/banner-initial.component.ts" }
angular/adev/src/content/examples/testing/src/app/banner/banner-external.component.spec.ts_0_2297
// #docplaster import {ComponentFixture, TestBed} from '@angular/core/testing'; import {BannerComponent} from './banner-external.component'; describe('BannerComponent (external files)', () => { let component: BannerComponent; let fixture: ComponentFixture<BannerComponent>; let h1: HTMLElement; describe('setup that may fail', () => { // #docregion setup-may-fail beforeEach(async () => { await TestBed.configureTestingModule({ imports: [BannerComponent], }); // missing call to compileComponents() fixture = TestBed.createComponent(BannerComponent); }); // #enddocregion setup-may-fail it('should create', () => { expect(fixture.componentInstance).toBeDefined(); }); }); describe('Two beforeEach', () => { // #docregion async-before-each beforeEach(async () => { await TestBed.configureTestingModule({ imports: [BannerComponent], }).compileComponents(); // compile template and css }); // #enddocregion async-before-each // synchronous beforeEach // #docregion sync-before-each beforeEach(() => { fixture = TestBed.createComponent(BannerComponent); component = fixture.componentInstance; // BannerComponent test instance h1 = fixture.nativeElement.querySelector('h1'); }); // #enddocregion sync-before-each tests(); }); describe('One beforeEach', () => { // #docregion one-before-each beforeEach(async () => { await TestBed.configureTestingModule({ imports: [BannerComponent], }).compileComponents(); fixture = TestBed.createComponent(BannerComponent); component = fixture.componentInstance; h1 = fixture.nativeElement.querySelector('h1'); }); // #enddocregion one-before-each tests(); }); function tests() { it('no title in the DOM until manually call `detectChanges`', () => { expect(h1.textContent).toEqual(''); }); it('should display original title', () => { fixture.detectChanges(); expect(h1.textContent).toContain(component.title); }); it('should display a different test title', () => { component.title = 'Test Title'; fixture.detectChanges(); expect(h1.textContent).toContain('Test Title'); }); } });
{ "end_byte": 2297, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/banner/banner-external.component.spec.ts" }
angular/adev/src/content/examples/testing/src/app/banner/banner-external.component.html_0_21
<h1>{{ title }}</h1>
{ "end_byte": 21, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/banner/banner-external.component.html" }
angular/adev/src/content/examples/testing/src/testing/jasmine-matchers.d.ts_0_169
// TODO: fix // declare namespace jasmine { // interface Matchers<T> { // toHaveText(actual: any, expectationFailOutput?: any): jasmine.CustomMatcher; // } // }
{ "end_byte": 169, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/testing/jasmine-matchers.d.ts" }
angular/adev/src/content/examples/testing/src/testing/jasmine-matchers.ts_0_1334
/// <reference path="./jasmine-matchers.d.ts" /> //// Jasmine Custom Matchers //// // Be sure to extend jasmine-matchers.d.ts when adding matchers export function addMatchers(): void { jasmine.addMatchers({ toHaveText, }); } function toHaveText(): jasmine.CustomMatcher { return { compare: ( actual: any, expectedText: string, expectationFailOutput?: any, ): jasmine.CustomMatcherResult => { const actualText = elementText(actual); const pass = actualText.indexOf(expectedText) > -1; const message = pass ? '' : composeMessage(); return {pass, message}; function composeMessage() { const a = actualText.length < 100 ? actualText : actualText.slice(0, 100) + '...'; const efo = expectationFailOutput ? ` '${expectationFailOutput}'` : ''; return `Expected element to have text content '${expectedText}' instead of '${a}'${efo}`; } }, }; } function elementText(n: any): string { if (n instanceof Array) { return n.map(elementText).join(''); } if (n.nodeType === Node.COMMENT_NODE) { return ''; } if (n.nodeType === Node.ELEMENT_NODE && n.hasChildNodes()) { return elementText(Array.prototype.slice.call(n.childNodes)); } if (n.nativeElement) { n = n.nativeElement; } return n.textContent; }
{ "end_byte": 1334, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/testing/jasmine-matchers.ts" }
angular/adev/src/content/examples/testing/src/testing/async-observable-helpers.ts_0_890
/* * Mock async observables that return asynchronously. * The observable either emits once and completes or errors. * * Must call `tick()` when test with `fakeAsync()`. * * THE FOLLOWING DON'T WORK * Using `of().delay()` triggers TestBed errors; * see https://github.com/angular/angular/issues/10127 . * * Using `asap` scheduler - as in `of(value, asap)` - doesn't work either. */ import {defer} from 'rxjs'; // #docregion async-data /** * Create async observable that emits-once and completes * after a JS engine turn */ export function asyncData<T>(data: T) { return defer(() => Promise.resolve(data)); } // #enddocregion async-data // #docregion async-error /** * Create async observable error that errors * after a JS engine turn */ export function asyncError<T>(errorObject: any) { return defer(() => Promise.reject(errorObject)); } // #enddocregion async-error
{ "end_byte": 890, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/testing/async-observable-helpers.ts" }
angular/adev/src/content/examples/testing/src/testing/index.ts_0_948
import {DebugElement} from '@angular/core'; import {ComponentFixture, tick} from '@angular/core/testing'; export * from './async-observable-helpers'; export * from './jasmine-matchers'; ///// Short utilities ///// /** Wait a tick, then detect changes */ export function advance(f: ComponentFixture<any>): void { tick(); f.detectChanges(); } // See https://developer.mozilla.org/docs/Web/API/MouseEvent/button // #docregion click-event /** Button events to pass to `DebugElement.triggerEventHandler` for RouterLink event handler */ export const ButtonClickEvents = { left: {button: 0}, right: {button: 2}, }; /** Simulate element click. Defaults to mouse left-button click event. */ export function click( el: DebugElement | HTMLElement, eventObj: any = ButtonClickEvents.left, ): void { if (el instanceof HTMLElement) { el.click(); } else { el.triggerEventHandler('click', eventObj); } } // #enddocregion click-event
{ "end_byte": 948, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/testing/index.ts" }
angular/adev/src/content/examples/ssr/readme.md_0_320
# Instructions for Angular SSR Example Download This is the downloaded sample code for the [Angular SSR (Standalone) guide](https://angular.io/guide/ssr). ## Install and Run 1. `npm install` to install the `node_module` packages 2. `ng serve` to launch the dev-server 3. Launch the browser to `http://localhost:4200`
{ "end_byte": 320, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/ssr/readme.md" }
angular/adev/src/content/examples/ssr/BUILD.bazel_0_84
package(default_visibility = ["//visibility:public"]) exports_files(["server.ts"])
{ "end_byte": 84, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/ssr/BUILD.bazel" }
angular/adev/src/content/examples/ssr/server.ts_0_1846
// #docplaster import {APP_BASE_HREF} from '@angular/common'; import {CommonEngine} from '@angular/ssr/node'; import express from 'express'; import {fileURLToPath} from 'node:url'; import {dirname, join, resolve} from 'node:path'; import bootstrap from './src/main.server'; // The Express app is exported so that it can be used by serverless Functions. export function app(): express.Express { const server = express(); const serverDistFolder = dirname(fileURLToPath(import.meta.url)); const browserDistFolder = resolve(serverDistFolder, '../browser'); const indexHtml = join(serverDistFolder, 'index.server.html'); const commonEngine = new CommonEngine(); server.set('view engine', 'html'); server.set('views', browserDistFolder); // TODO: implement data requests securely // Serve data from URLS that begin "/api/" server.get('/api/**', (req, res) => { res.status(404).send('data requests are not yet supported'); }); // Serve static files from /browser server.get( '*.*', express.static(browserDistFolder, { maxAge: '1y', }), ); // All regular routes use the Angular engine server.get('*', (req, res, next) => { const {protocol, originalUrl, baseUrl, headers} = req; commonEngine .render({ bootstrap, documentFilePath: indexHtml, url: `${protocol}://${headers.host}${originalUrl}`, publicPath: browserDistFolder, providers: [{provide: APP_BASE_HREF, useValue: req.baseUrl}], }) .then((html) => res.send(html)) .catch((err) => next(err)); }); return server; } function run(): void { const port = process.env['PORT'] || 4000; // Start up the Node server const server = app(); server.listen(port, () => { console.log(`Node Express server listening on http://localhost:${port}`); }); } run();
{ "end_byte": 1846, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/ssr/server.ts" }
angular/adev/src/content/examples/ssr/e2e/src/app.e2e-spec.ts_0_1074
import {browser, by, element, ElementArrayFinder, ElementFinder, logging} from 'protractor'; class Hero { constructor( public id: number, public name: string, ) {} // Factory methods // Hero from string formatted as '<id> <name>'. static fromString(s: string): Hero { return new Hero(+s.substring(0, s.indexOf(' ')), s.slice(s.indexOf(' ') + 1)); } // Hero from hero list <li> element. static async fromLi(li: ElementFinder): Promise<Hero> { const stringsFromA = await li.all(by.css('a')).getText(); const strings = stringsFromA[0].split(' '); return {id: +strings[0], name: strings[1]}; } // Hero id and name from the given detail element. static async fromDetail(detail: ElementFinder): Promise<Hero> { // Get hero id from the first <div> const id = await detail.all(by.css('div')).first().getText(); // Get name from the h2 const name = await detail.element(by.css('h2')).getText(); return { id: +id.slice(id.indexOf(' ') + 1), name: name.substring(0, name.lastIndexOf(' ')), }; } }
{ "end_byte": 1074, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/ssr/e2e/src/app.e2e-spec.ts" }
angular/adev/src/content/examples/ssr/e2e/src/app.e2e-spec.ts_1076_9607
describe('Universal', () => { const expectedH1 = 'Tour of Heroes'; const expectedTitle = `${expectedH1}`; const targetHero = {id: 15, name: 'Magneta'}; const targetHeroDashboardIndex = 2; const nameSuffix = 'X'; const newHeroName = targetHero.name + nameSuffix; afterEach(async () => { // Assert that there are no errors emitted from the browser const logs = await browser.manage().logs().get(logging.Type.BROWSER); const severeLogs = logs.filter((entry) => entry.level === logging.Level.SEVERE); expect(severeLogs).toEqual([]); }); describe('Initial page', () => { beforeAll(() => browser.get('')); it(`has title '${expectedTitle}'`, async () => { expect(await browser.getTitle()).toEqual(expectedTitle); }); it(`has h1 '${expectedH1}'`, async () => { await expectHeading(1, expectedH1); }); const expectedViewNames = ['Dashboard', 'Heroes']; it(`has views ${expectedViewNames}`, async () => { const viewNames = await getPageElts().navElts.map((el) => el!.getText()); expect(viewNames).toEqual(expectedViewNames); }); it('has dashboard as the active view', async () => { const page = getPageElts(); expect(await page.appDashboard.isPresent()).toBeTruthy(); }); }); describe('Dashboard tests', () => { beforeAll(() => browser.get('')); it('has top heroes', async () => { const page = getPageElts(); expect(await page.topHeroes.count()).toEqual(4); }); it(`selects and routes to ${targetHero.name} details`, dashboardSelectTargetHero); it(`updates hero name (${newHeroName}) in details view`, updateHeroNameInDetailView); it(`cancels and shows ${targetHero.name} in Dashboard`, async () => { await element(by.buttonText('go back')).click(); await browser.waitForAngular(); // seems necessary to gets tests to pass for toh-pt6 const targetHeroElt = getPageElts().topHeroes.get(targetHeroDashboardIndex); expect(await targetHeroElt.getText()).toEqual(targetHero.name); }); it(`selects and routes to ${targetHero.name} details`, dashboardSelectTargetHero); it(`updates hero name (${newHeroName}) in details view`, updateHeroNameInDetailView); it(`saves and shows ${newHeroName} in Dashboard`, async () => { await element(by.buttonText('save')).click(); await browser.waitForAngular(); // seems necessary to gets tests to pass for toh-pt6 const targetHeroElt = getPageElts().topHeroes.get(targetHeroDashboardIndex); expect(await targetHeroElt.getText()).toEqual(newHeroName); }); }); describe('Heroes tests', () => { beforeAll(() => browser.get('')); it('can switch to Heroes view', async () => { await getPageElts().appHeroesHref.click(); const page = getPageElts(); expect(await page.appHeroes.isPresent()).toBeTruthy(); expect(await page.allHeroes.count()).toEqual(9, 'number of heroes'); }); it('can route to hero details', async () => { await getHeroLiEltById(targetHero.id).click(); const page = getPageElts(); expect(await page.heroDetail.isPresent()).toBeTruthy('shows hero detail'); const hero = await Hero.fromDetail(page.heroDetail); expect(hero.id).toEqual(targetHero.id); expect(hero.name).toEqual(targetHero.name.toUpperCase()); }); it(`updates hero name (${newHeroName}) in details view`, updateHeroNameInDetailView); it(`shows ${newHeroName} in Heroes list`, async () => { await element(by.buttonText('save')).click(); await browser.waitForAngular(); const expectedText = `${targetHero.id} ${newHeroName}`; expect(await getHeroAEltById(targetHero.id).getText()).toEqual(expectedText); }); it(`deletes ${newHeroName} from Heroes list`, async () => { const heroesBefore = await toHeroArray(getPageElts().allHeroes); const li = getHeroLiEltById(targetHero.id); await li.element(by.buttonText('x')).click(); const page = getPageElts(); expect(await page.appHeroes.isPresent()).toBeTruthy(); expect(await page.allHeroes.count()).toEqual(8, 'number of heroes'); const heroesAfter = await toHeroArray(page.allHeroes); // console.log(await Hero.fromLi(page.allHeroes[0])); const expectedHeroes = heroesBefore.filter((h) => h.name !== newHeroName); expect(heroesAfter).toEqual(expectedHeroes); // expect(await page.selectedHeroSubview.isPresent()).toBeFalsy(); }); it(`adds back ${targetHero.name}`, async () => { const updatedHeroName = 'Alice'; const heroesBefore = await toHeroArray(getPageElts().allHeroes); const numHeroes = heroesBefore.length; await element(by.css('input')).sendKeys(updatedHeroName); await element(by.buttonText('add')).click(); const page = getPageElts(); const heroesAfter = await toHeroArray(page.allHeroes); expect(heroesAfter.length).toEqual(numHeroes + 1, 'number of heroes'); expect(heroesAfter.slice(0, numHeroes)).toEqual(heroesBefore, 'Old heroes are still there'); const maxId = heroesBefore[heroesBefore.length - 1].id; expect(heroesAfter[numHeroes]).toEqual({id: maxId + 1, name: updatedHeroName}); }); it('displays correctly styled buttons', async () => { const buttons = await element.all(by.buttonText('x')); for (const button of buttons) { // Inherited styles from styles.css expect(await button.getCssValue('font-family')).toBe('Arial, sans-serif'); expect(await button.getCssValue('border')).toContain('none'); expect(await button.getCssValue('padding')).toBe('5px 10px'); expect(await button.getCssValue('border-radius')).toBe('4px'); // Styles defined in heroes.component.css expect(await button.getCssValue('right')).toBe('0px'); expect(await button.getCssValue('top')).toBe('0px'); expect(await button.getCssValue('bottom')).toBe('0px'); } const addButton = element(by.buttonText('add')); // Inherited styles from styles.css expect(await addButton.getCssValue('font-family')).toBe('Arial, sans-serif'); expect(await addButton.getCssValue('border')).toContain('none'); expect(await addButton.getCssValue('padding')).toBe('5px 10px'); expect(await addButton.getCssValue('border-radius')).toBe('4px'); }); }); describe('Progressive hero search', () => { beforeAll(() => browser.get('')); it(`searches for 'Ma'`, async () => { await getPageElts().searchBox.sendKeys('Ma'); await browser.sleep(1000); expect(await getPageElts().searchResults.count()).toBe(4); }); it(`continues search with 'g'`, async () => { await getPageElts().searchBox.sendKeys('g'); await browser.sleep(1000); expect(await getPageElts().searchResults.count()).toBe(2); }); it(`continues search with 'n' and gets ${targetHero.name}`, async () => { await getPageElts().searchBox.sendKeys('n'); await browser.sleep(1000); const page = getPageElts(); expect(await page.searchResults.count()).toBe(1); const hero = page.searchResults.get(0); expect(await hero.getText()).toEqual(targetHero.name); }); it(`navigates to ${targetHero.name} details view`, async () => { const hero = getPageElts().searchResults.get(0); expect(await hero.getText()).toEqual(targetHero.name); await hero.click(); const page = getPageElts(); expect(await page.heroDetail.isPresent()).toBeTruthy('shows hero detail'); const hero2 = await Hero.fromDetail(page.heroDetail); expect(hero2.id).toEqual(targetHero.id); expect(hero2.name).toEqual(targetHero.name.toUpperCase()); }); }); // Helpers async function addToHeroName(text: string): Promise<void> { await element(by.css('input')).sendKeys(text); } async function dashboardSelectTargetHero(): Promise<void> { const targetHeroElt = getPageElts().topHeroes.get(targetHeroDashboardIndex); expect(await targetHeroElt.getText()).toEqual(targetHero.name); await targetHeroElt.click(); await browser.waitForAngular(); // seems necessary to gets tests to pass for toh-pt6 const page = getPageElts(); expect(await page.heroDetail.isPresent()).toBeTruthy('shows hero detail'); const hero = await Hero.fromDetail(page.heroDetail); expect(hero.id).toEqual(targetHero.id); expect(hero.name).toEqual(targetHero.name.toUpperCase()); }
{ "end_byte": 9607, "start_byte": 1076, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/ssr/e2e/src/app.e2e-spec.ts" }
angular/adev/src/content/examples/ssr/e2e/src/app.e2e-spec.ts_9611_11461
async function expectHeading(hLevel: number, expectedText: string): Promise<void> { const hTag = `h${hLevel}`; const hText = await element(by.css(hTag)).getText(); expect(hText).toEqual(expectedText, hTag); } function getHeroAEltById(id: number): ElementFinder { const spanForId = element(by.cssContainingText('li span.badge', id.toString())); return spanForId.element(by.xpath('..')); } function getHeroLiEltById(id: number): ElementFinder { const spanForId = element(by.cssContainingText('li span.badge', id.toString())); return spanForId.element(by.xpath('../..')); } function getPageElts() { const navElts = element.all(by.css('app-root nav a')); return { navElts, appDashboardHref: navElts.get(0), appDashboard: element(by.css('app-root app-dashboard')), topHeroes: element.all(by.css('app-root app-dashboard > div h4')), appHeroesHref: navElts.get(1), appHeroes: element(by.css('app-root app-heroes')), allHeroes: element.all(by.css('app-root app-heroes li')), selectedHeroSubview: element(by.css('app-root app-heroes > div:last-child')), heroDetail: element(by.css('app-root app-hero-detail > div')), searchBox: element(by.css('#search-box')), searchResults: element.all(by.css('.search-result li')), }; } async function toHeroArray(allHeroes: ElementArrayFinder): Promise<Hero[]> { return await allHeroes.map((hero) => Hero.fromLi(hero!)); } async function updateHeroNameInDetailView(): Promise<void> { // Assumes that the current view is the hero details view. await addToHeroName(nameSuffix); const page = getPageElts(); const hero = await Hero.fromDetail(page.heroDetail); expect(hero.id).toEqual(targetHero.id); expect(hero.name).toEqual(newHeroName.toUpperCase()); } });
{ "end_byte": 11461, "start_byte": 9611, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/ssr/e2e/src/app.e2e-spec.ts" }
angular/adev/src/content/examples/ssr/src/index.html_0_300
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Tour of Heroes</title> <base href="/"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" type="image/x-icon" href="favicon.ico"> </head> <body> <app-root></app-root> </body> </html>
{ "end_byte": 300, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/ssr/src/index.html" }
angular/adev/src/content/examples/ssr/src/main.ts_0_241
import {bootstrapApplication} from '@angular/platform-browser'; import {AppComponent} from './app/app.component'; import {appConfig} from './app/app.config'; bootstrapApplication(AppComponent, appConfig).catch((err) => console.error(err));
{ "end_byte": 241, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/ssr/src/main.ts" }
angular/adev/src/content/examples/ssr/src/main.server.ts_0_257
import {bootstrapApplication} from '@angular/platform-browser'; import {AppComponent} from './app/app.component'; import {config} from './app/app.config.server'; const bootstrap = () => bootstrapApplication(AppComponent, config); export default bootstrap;
{ "end_byte": 257, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/ssr/src/main.server.ts" }
angular/adev/src/content/examples/ssr/src/app/app.component.html_0_174
<h1>{{title}}</h1> <nav> <a routerLink="/dashboard">Dashboard</a> <a routerLink="/heroes">Heroes</a> </nav> <router-outlet></router-outlet> <app-messages></app-messages>
{ "end_byte": 174, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/ssr/src/app/app.component.html" }
angular/adev/src/content/examples/ssr/src/app/message.service.ts_0_240
import {Injectable} from '@angular/core'; @Injectable({providedIn: 'root'}) export class MessageService { messages: string[] = []; add(message: string) { this.messages.push(message); } clear() { this.messages = []; } }
{ "end_byte": 240, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/ssr/src/app/message.service.ts" }
angular/adev/src/content/examples/ssr/src/app/in-memory-data.service.ts_0_984
import {Injectable} from '@angular/core'; import {InMemoryDbService} from 'angular-in-memory-web-api'; import {Hero} from './hero'; @Injectable({ providedIn: 'root', }) export class InMemoryDataService implements InMemoryDbService { createDb() { const heroes = [ {id: 12, name: 'Dr. Nice'}, {id: 13, name: 'Bombasto'}, {id: 14, name: 'Celeritas'}, {id: 15, name: 'Magneta'}, {id: 16, name: 'RubberMan'}, {id: 17, name: 'Dynama'}, {id: 18, name: 'Dr. IQ'}, {id: 19, name: 'Magma'}, {id: 20, name: 'Tornado'}, ]; return {heroes}; } // Overrides the genId method to ensure that a hero always has an id. // If the heroes array is empty, // the method below returns the initial number (11). // if the heroes array is not empty, the method below returns the highest // hero id + 1. genId(heroes: Hero[]): number { return heroes.length > 0 ? Math.max(...heroes.map((hero) => hero.id)) + 1 : 11; } }
{ "end_byte": 984, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/ssr/src/app/in-memory-data.service.ts" }
angular/adev/src/content/examples/ssr/src/app/hero.ts_0_56
export interface Hero { id: number; name: string; }
{ "end_byte": 56, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/ssr/src/app/hero.ts" }
angular/adev/src/content/examples/ssr/src/app/app.config.server.ts_0_337
import {mergeApplicationConfig, ApplicationConfig} from '@angular/core'; import {provideServerRendering} from '@angular/platform-server'; import {appConfig} from './app.config'; const serverConfig: ApplicationConfig = { providers: [provideServerRendering()], }; export const config = mergeApplicationConfig(appConfig, serverConfig);
{ "end_byte": 337, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/ssr/src/app/app.config.server.ts" }
angular/adev/src/content/examples/ssr/src/app/mock-heroes.ts_0_328
import {Hero} from './hero'; export const HEROES: Hero[] = [ {id: 12, name: 'Dr. Nice'}, {id: 13, name: 'Bombasto'}, {id: 14, name: 'Celeritas'}, {id: 15, name: 'Magneta'}, {id: 16, name: 'RubberMan'}, {id: 17, name: 'Dynama'}, {id: 18, name: 'Dr. IQ'}, {id: 19, name: 'Magma'}, {id: 20, name: 'Tornado'}, ];
{ "end_byte": 328, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/ssr/src/app/mock-heroes.ts" }
angular/adev/src/content/examples/ssr/src/app/app.routes.ts_0_494
import {Routes} from '@angular/router'; import {DashboardComponent} from './dashboard/dashboard.component'; import {HeroesComponent} from './heroes/heroes.component'; import {HeroDetailComponent} from './hero-detail/hero-detail.component'; export const routes: Routes = [ {path: '', redirectTo: '/dashboard', pathMatch: 'full'}, {path: 'dashboard', component: DashboardComponent}, {path: 'detail/:id', component: HeroDetailComponent}, {path: 'heroes', component: HeroesComponent}, ];
{ "end_byte": 494, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/ssr/src/app/app.routes.ts" }
angular/adev/src/content/examples/ssr/src/app/app.component.ts_0_772
import {Component} from '@angular/core'; import {RouterLink, RouterOutlet} from '@angular/router'; import {PLATFORM_ID, APP_ID, Inject} from '@angular/core'; import {isPlatformBrowser} from '@angular/common'; import {MessagesComponent} from './messages/messages.component'; @Component({ standalone: true, selector: 'app-root', templateUrl: './app.component.html', imports: [RouterLink, RouterOutlet, MessagesComponent], styleUrls: ['./app.component.css'], }) export class AppComponent { title = 'Tour of Heroes'; constructor(@Inject(PLATFORM_ID) platformId: object, @Inject(APP_ID) appId: string) { const platform = isPlatformBrowser(platformId) ? 'in the browser' : 'on the server'; console.log(`Running ${platform} with appId=${appId}`); } }
{ "end_byte": 772, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/ssr/src/app/app.component.ts" }
angular/adev/src/content/examples/ssr/src/app/app.config.ts_0_1149
// #docplaster import {importProvidersFrom} from '@angular/core'; import {provideProtractorTestingSupport} from '@angular/platform-browser'; import {provideClientHydration} from '@angular/platform-browser'; import {ApplicationConfig} from '@angular/core'; import {provideRouter} from '@angular/router'; import {provideHttpClient, withFetch} from '@angular/common/http'; import {routes} from './app.routes'; import {HttpClientInMemoryWebApiModule} from 'angular-in-memory-web-api'; import {InMemoryDataService} from './in-memory-data.service'; export const appConfig: ApplicationConfig = { providers: [ provideRouter(routes), provideHttpClient(withFetch()), provideClientHydration(), provideProtractorTestingSupport(), // essential for e2e testing // TODO: Remove from production apps importProvidersFrom( // The HttpClientInMemoryWebApiModule module intercepts HTTP requests // and returns simulated server responses. // Remove it when a real server is ready to receive requests. HttpClientInMemoryWebApiModule.forRoot(InMemoryDataService, {dataEncapsulation: false}), ), // ... ], };
{ "end_byte": 1149, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/ssr/src/app/app.config.ts" }
angular/adev/src/content/examples/ssr/src/app/app.component.css_0_378
/* AppComponent's private CSS styles */ h1 { font-size: 1.2em; margin-bottom: 0; } nav a { padding: 5px 10px; text-decoration: none; margin-top: 10px; display: inline-block; background-color: #eee; border-radius: 4px; } nav a:visited, a:link { color: #334953; } nav a:hover { color: #039be5; background-color: #CFD8DC; } nav a.active { color: #039be5; }
{ "end_byte": 378, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/ssr/src/app/app.component.css" }
angular/adev/src/content/examples/ssr/src/app/hero.service.ts_0_3957
import {Injectable} from '@angular/core'; import {HttpClient, HttpHeaders} from '@angular/common/http'; import {Observable, of} from 'rxjs'; import {catchError, map, tap} from 'rxjs/operators'; import {Hero} from './hero'; import {MessageService} from './message.service'; @Injectable({providedIn: 'root'}) export class HeroService { private heroesUrl = 'api/heroes'; // URL to web api httpOptions = { headers: new HttpHeaders({'Content-Type': 'application/json'}), }; constructor( private http: HttpClient, private messageService: MessageService, ) {} /** GET heroes from the server */ getHeroes(): Observable<Hero[]> { return this.http.get<Hero[]>(this.heroesUrl).pipe( tap((_) => this.log('fetched heroes')), catchError(this.handleError<Hero[]>('getHeroes', [])), ); } /** GET hero by id. Return `undefined` when id not found */ getHeroNo404<Data>(id: number): Observable<Hero> { const url = `${this.heroesUrl}/?id=${id}`; return this.http.get<Hero[]>(url).pipe( map((heroes) => heroes[0]), // returns a {0|1} element array tap((h) => { const outcome = h ? 'fetched' : 'did not find'; this.log(`${outcome} hero id=${id}`); }), catchError(this.handleError<Hero>(`getHero id=${id}`)), ); } /** GET hero by id. Will 404 if id not found */ getHero(id: number): Observable<Hero> { const url = `${this.heroesUrl}/${id}`; return this.http.get<Hero>(url).pipe( tap((_) => this.log(`fetched hero id=${id}`)), catchError(this.handleError<Hero>(`getHero id=${id}`)), ); } /* GET heroes whose name contains search term */ searchHeroes(term: string): Observable<Hero[]> { if (!term.trim()) { // if not search term, return empty hero array. return of([]); } return this.http.get<Hero[]>(`${this.heroesUrl}/?name=${term}`).pipe( tap((x) => x.length ? this.log(`found heroes matching "${term}"`) : this.log(`no heroes matching "${term}"`), ), catchError(this.handleError<Hero[]>('searchHeroes', [])), ); } //////// Save methods ////////// /** POST: add a new hero to the server */ addHero(hero: Hero): Observable<Hero> { return this.http.post<Hero>(this.heroesUrl, hero, this.httpOptions).pipe( tap((newHero: Hero) => this.log(`added hero w/ id=${newHero.id}`)), catchError(this.handleError<Hero>('addHero')), ); } /** DELETE: delete the hero from the server */ deleteHero(hero: Hero | number): Observable<Hero> { const id = typeof hero === 'number' ? hero : hero.id; const url = `${this.heroesUrl}/${id}`; return this.http.delete<Hero>(url, this.httpOptions).pipe( tap((_) => this.log(`deleted hero id=${id}`)), catchError(this.handleError<Hero>('deleteHero')), ); } /** PUT: update the hero on the server */ updateHero(hero: Hero): Observable<any> { return this.http.put(this.heroesUrl, hero, this.httpOptions).pipe( tap((_) => this.log(`updated hero id=${hero.id}`)), catchError(this.handleError<any>('updateHero')), ); } /** * Handle Http operation that failed. * Let the app continue. * * @param operation - name of the operation that failed * @param result - optional value to return as the observable result */ private handleError<T>(operation = 'operation', result?: T) { return (error: any): Observable<T> => { // TODO: send the error to remote logging infrastructure console.error(error); // log to console instead // TODO: better job of transforming error for user consumption this.log(`${operation} failed: ${error.message}`); // Let the app keep running by returning an empty result. return of(result as T); }; } /** Log a HeroService message with the MessageService */ private log(message: string) { this.messageService.add(`HeroService: ${message}`); } }
{ "end_byte": 3957, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/ssr/src/app/hero.service.ts" }
angular/adev/src/content/examples/ssr/src/app/messages/messages.component.html_0_255
<div *ngIf="messageService.messages.length"> <h2>Messages</h2> <button type="button" class="clear" (click)="messageService.clear()">clear</button> <div *ngFor='let message of messageService.messages'> {{message}} </div> </div>
{ "end_byte": 255, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/ssr/src/app/messages/messages.component.html" }
angular/adev/src/content/examples/ssr/src/app/messages/messages.component.ts_0_407
import {Component} from '@angular/core'; import {NgFor, NgIf} from '@angular/common'; import {MessageService} from '../message.service'; @Component({ standalone: true, selector: 'app-messages', templateUrl: './messages.component.html', imports: [NgFor, NgIf], styleUrls: ['./messages.component.css'], }) export class MessagesComponent { constructor(public messageService: MessageService) {} }
{ "end_byte": 407, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/ssr/src/app/messages/messages.component.ts" }
angular/adev/src/content/examples/ssr/src/app/messages/messages.component.css_0_375
/* MessagesComponent's private CSS styles */ h2 { color: red; font-family: Arial, Helvetica, sans-serif; font-weight: lighter; } button.clear { font-family: Arial, sans-serif; color: #333; background-color: #eee; margin-bottom: 12px; border: none; padding: 5px 10px; border-radius: 4px; cursor: pointer; } button:hover { background-color: #cfd8dc; }
{ "end_byte": 375, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/ssr/src/app/messages/messages.component.css" }
angular/adev/src/content/examples/ssr/src/app/heroes/heroes.component.css_0_1177
/* HeroesComponent's private CSS styles */ .heroes { margin: 0 0 2em 0; list-style-type: none; padding: 0; width: 15em; } .heroes li { position: relative; cursor: pointer; background-color: #EEE; margin: .5em; padding: .3em 0; height: 1.6em; border-radius: 4px; } .heroes li:hover { color: #607D8B; background-color: #DDD; left: .1em; } .heroes a { color: #333; text-decoration: none; position: relative; display: block; width: 250px; } .heroes a:hover { color: #607D8B; } .heroes .badge { display: inline-block; font-size: small; color: white; padding: 0.8em 0.7em 0 0.7em; background-color: #405061; line-height: 1em; position: relative; left: -1px; top: -4px; height: 1.8em; min-width: 16px; text-align: right; margin-right: .8em; border-radius: 4px 0 0 4px; } button { background-color: #eee; border: none; padding: 5px 10px; border-radius: 4px; cursor: pointer; font-family: Arial, sans-serif; } button:hover { background-color: #cfd8dc; } button.delete { position: absolute; right: 0; top: 0; bottom: 0; background-color: gray !important; color: white; margin: 0; }
{ "end_byte": 1177, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/ssr/src/app/heroes/heroes.component.css" }
angular/adev/src/content/examples/ssr/src/app/heroes/heroes.component.html_0_556
<h2>My Heroes</h2> <div> <label for="name">Hero name: <input id="name" #heroName /> </label> <!-- (click) passes input value to add() and then clears the input --> <button type="button" (click)="add(heroName.value); heroName.value=''"> add </button> </div> <ul class="heroes"> <li *ngFor="let hero of heroes"> <a routerLink="/detail/{{hero.id}}"> <span class="badge">{{hero.id}}</span> {{hero.name}} </a> <button type="button" class="delete" title="delete hero" (click)="delete(hero)">x</button> </li> </ul>
{ "end_byte": 556, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/ssr/src/app/heroes/heroes.component.html" }
angular/adev/src/content/examples/ssr/src/app/heroes/heroes.component.ts_0_1002
import {Component, OnInit} from '@angular/core'; import {NgFor} from '@angular/common'; import {RouterLink} from '@angular/router'; import {Hero} from '../hero'; import {HeroService} from '../hero.service'; @Component({ standalone: true, selector: 'app-heroes', templateUrl: './heroes.component.html', imports: [NgFor, RouterLink], styleUrls: ['./heroes.component.css'], }) export class HeroesComponent implements OnInit { heroes: Hero[] = []; constructor(private heroService: HeroService) {} ngOnInit() { this.getHeroes(); } getHeroes(): void { this.heroService.getHeroes().subscribe((heroes) => (this.heroes = heroes)); } add(name: string): void { name = name.trim(); if (!name) { return; } this.heroService.addHero({name} as Hero).subscribe((hero) => { this.heroes.push(hero); }); } delete(hero: Hero): void { this.heroes = this.heroes.filter((h) => h !== hero); this.heroService.deleteHero(hero).subscribe(); } }
{ "end_byte": 1002, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/ssr/src/app/heroes/heroes.component.ts" }
angular/adev/src/content/examples/ssr/src/app/hero-detail/hero-detail.component.ts_0_1064
import {Component, OnInit, Input} from '@angular/core'; import {ActivatedRoute} from '@angular/router'; import {Location, NgIf, UpperCasePipe} from '@angular/common'; import {FormsModule} from '@angular/forms'; import {Hero} from '../hero'; import {HeroService} from '../hero.service'; @Component({ standalone: true, selector: 'app-hero-detail', templateUrl: './hero-detail.component.html', imports: [FormsModule, NgIf, UpperCasePipe], styleUrls: ['./hero-detail.component.css'], }) export class HeroDetailComponent implements OnInit { @Input() hero!: Hero; constructor( private route: ActivatedRoute, private heroService: HeroService, private location: Location, ) {} ngOnInit(): void { this.getHero(); } getHero(): void { const id = parseInt(this.route.snapshot.paramMap.get('id')!, 10); this.heroService.getHero(id).subscribe((hero) => (this.hero = hero)); } goBack(): void { this.location.back(); } save(): void { this.heroService.updateHero(this.hero).subscribe(() => this.goBack()); } }
{ "end_byte": 1064, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/ssr/src/app/hero-detail/hero-detail.component.ts" }
angular/adev/src/content/examples/ssr/src/app/hero-detail/hero-detail.component.css_0_510
/* HeroDetailComponent's private CSS styles */ label { display: inline-block; width: 3em; margin: .5em 0; color: #607D8B; font-weight: bold; } input { height: 2em; font-size: 1em; padding-left: .4em; } button { margin-top: 20px; font-family: Arial, sans-serif; background-color: #eee; border: none; padding: 5px 10px; border-radius: 4px; cursor: pointer; } button:hover { background-color: #cfd8dc; } button:disabled { background-color: #eee; color: #ccc; cursor: auto; }
{ "end_byte": 510, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/ssr/src/app/hero-detail/hero-detail.component.css" }
angular/adev/src/content/examples/ssr/src/app/hero-detail/hero-detail.component.html_0_354
<div *ngIf="hero"> <h2>{{hero.name | uppercase}} Details</h2> <div><span>id: </span>{{hero.id}}</div> <div> <label for="name">name: <input id="name" [(ngModel)]="hero.name" placeholder="name"/> </label> </div> <button type="button" (click)="goBack()">go back</button> <button type="button" (click)="save()">save</button> </div>
{ "end_byte": 354, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/ssr/src/app/hero-detail/hero-detail.component.html" }
angular/adev/src/content/examples/ssr/src/app/hero-search/hero-search.component.html_0_335
<div id="search-component"> <h4><label for="search-box">Hero Search</label></h4> <input #searchBox id="search-box" (input)="search(searchBox.value)" /> <ul class="search-result"> <li *ngFor="let hero of heroes$ | async" > <a routerLink="/detail/{{hero.id}}"> {{hero.name}} </a> </li> </ul> </div>
{ "end_byte": 335, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/ssr/src/app/hero-search/hero-search.component.html" }
angular/adev/src/content/examples/ssr/src/app/hero-search/hero-search.component.ts_0_1243
import {Component, OnInit} from '@angular/core'; import {AsyncPipe, NgFor} from '@angular/common'; import {RouterLink} from '@angular/router'; import {Observable, Subject} from 'rxjs'; import {debounceTime, distinctUntilChanged, switchMap} from 'rxjs/operators'; import {Hero} from '../hero'; import {HeroService} from '../hero.service'; @Component({ standalone: true, selector: 'app-hero-search', templateUrl: './hero-search.component.html', imports: [AsyncPipe, NgFor, RouterLink], styleUrls: ['./hero-search.component.css'], }) export class HeroSearchComponent implements OnInit { heroes$!: Observable<Hero[]>; private searchTerms = new Subject<string>(); constructor(private heroService: HeroService) {} // Push a search term into the observable stream. search(term: string): void { this.searchTerms.next(term); } ngOnInit(): void { this.heroes$ = this.searchTerms.pipe( // wait 300ms after each keystroke before considering the term debounceTime(300), // ignore new term if same as previous term distinctUntilChanged(), // switch to new search observable each time the term changes switchMap((term: string) => this.heroService.searchHeroes(term)), ); } }
{ "end_byte": 1243, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/ssr/src/app/hero-search/hero-search.component.ts" }
angular/adev/src/content/examples/ssr/src/app/hero-search/hero-search.component.css_0_611
/* HeroSearch private styles */ .search-result li { border-bottom: 1px solid gray; border-left: 1px solid gray; border-right: 1px solid gray; width: 195px; height: 16px; padding: 5px; background-color: white; cursor: pointer; list-style-type: none; } .search-result li:hover { background-color: #607D8B; } .search-result li a { color: #888; display: block; text-decoration: none; } .search-result li a:hover { color: white; } .search-result li a:active { color: white; } #search-box { width: 200px; height: 20px; } ul.search-result { margin-top: 0; padding-left: 0; }
{ "end_byte": 611, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/ssr/src/app/hero-search/hero-search.component.css" }
angular/adev/src/content/examples/ssr/src/app/dashboard/dashboard.component.css_0_917
/* DashboardComponent's private CSS styles */ [class*='col-'] { float: left; padding-right: 20px; padding-bottom: 20px; } [class*='col-']:last-of-type { padding-right: 0; } a { text-decoration: none; } *, *::after, *::before { box-sizing: border-box; } h3 { text-align: center; margin-bottom: 0; } h4 { position: relative; } .grid { margin: 0; } .col-1-4 { width: 25%; } .module { padding: 20px; text-align: center; color: #eee; max-height: 120px; min-width: 120px; background-color: #3f525c; border-radius: 2px; } .module:hover { background-color: #EEE; cursor: pointer; color: #607d8b; } .grid-pad { padding: 10px 0; } .grid-pad > [class*='col-']:last-of-type { padding-right: 20px; } @media (max-width: 600px) { .module { font-size: 10px; max-height: 75px; } } @media (max-width: 1024px) { .grid { margin: 0; } .module { min-width: 60px; } }
{ "end_byte": 917, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/ssr/src/app/dashboard/dashboard.component.css" }
angular/adev/src/content/examples/ssr/src/app/dashboard/dashboard.component.html_0_258
<h3>Top Heroes</h3> <div class="grid grid-pad"> <a *ngFor="let hero of heroes" class="col-1-4" routerLink="/detail/{{hero.id}}"> <div class="module hero"> <h4>{{hero.name}}</h4> </div> </a> </div> <app-hero-search></app-hero-search>
{ "end_byte": 258, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/ssr/src/app/dashboard/dashboard.component.html" }
angular/adev/src/content/examples/ssr/src/app/dashboard/dashboard.component.ts_0_780
import {Component, OnInit} from '@angular/core'; import {NgFor} from '@angular/common'; import {RouterLink} from '@angular/router'; import {Hero} from '../hero'; import {HeroSearchComponent} from '../hero-search/hero-search.component'; import {HeroService} from '../hero.service'; @Component({ standalone: true, selector: 'app-dashboard', templateUrl: './dashboard.component.html', imports: [NgFor, RouterLink, HeroSearchComponent], styleUrls: ['./dashboard.component.css'], }) export class DashboardComponent implements OnInit { heroes: Hero[] = []; constructor(private heroService: HeroService) {} ngOnInit() { this.getHeroes(); } getHeroes(): void { this.heroService.getHeroes().subscribe((heroes) => (this.heroes = heroes.slice(1, 5))); } }
{ "end_byte": 780, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/ssr/src/app/dashboard/dashboard.component.ts" }
angular/adev/src/content/examples/elements/BUILD.bazel_0_172
package(default_visibility = ["//visibility:public"]) exports_files([ "src/app/app.component.ts", "src/app/popup.component.ts", "src/app/popup.service.ts", ])
{ "end_byte": 172, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/elements/BUILD.bazel" }
angular/adev/src/content/examples/elements/e2e/src/app.e2e-spec.ts_0_2773
import {browser, by, element, ElementFinder, ExpectedConditions as EC} from 'protractor'; describe('Elements', () => { const messageInput = element(by.css('input')); const popupButtons = element.all(by.css('button')); // Helpers const click = async (elem: ElementFinder) => { // Waiting for the element to be clickable, makes the tests less flaky. await browser.wait(EC.elementToBeClickable(elem), 5000); await elem.click(); }; const waitForText = async (elem: ElementFinder) => { // Waiting for the element to have some text, makes the tests less flaky. await browser.wait(async () => /\S/.test(await elem.getText()), 5000); }; beforeEach(() => browser.get('')); describe('popup component', () => { const popupComponentButton = popupButtons.get(0); const popupComponent = element(by.css('popup-component')); const closeButton = popupComponent.element(by.css('button')); it('should be displayed on button click', async () => { expect(await popupComponent.isPresent()).toBe(false); await click(popupComponentButton); expect(await popupComponent.isPresent()).toBe(true); }); it('should display the specified message', async () => { await messageInput.clear(); await messageInput.sendKeys('Angular rocks!'); await click(popupComponentButton); await waitForText(popupComponent); expect(await popupComponent.getText()).toContain('Popup: Angular rocks!'); }); it('should be closed on "close" button click', async () => { await click(popupComponentButton); expect(await popupComponent.isPresent()).toBe(true); await click(closeButton); expect(await popupComponent.isPresent()).toBe(false); }); }); describe('popup element', () => { const popupElementButton = popupButtons.get(1); const popupElement = element(by.css('popup-element')); const closeButton = popupElement.element(by.css('button')); it('should be displayed on button click', async () => { expect(await popupElement.isPresent()).toBe(false); await click(popupElementButton); expect(await popupElement.isPresent()).toBe(true); }); it('should display the specified message', async () => { await messageInput.clear(); await messageInput.sendKeys('Angular rocks!'); await click(popupElementButton); await waitForText(popupElement); expect(await popupElement.getText()).toContain('Popup: Angular rocks!'); }); it('should be closed on "close" button click', async () => { await click(popupElementButton); expect(await popupElement.isPresent()).toBe(true); await click(closeButton); expect(await popupElement.isPresent()).toBe(false); }); }); });
{ "end_byte": 2773, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/elements/e2e/src/app.e2e-spec.ts" }
angular/adev/src/content/examples/elements/src/index.html_0_253
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <base href="/"> <title>Elements</title> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <app-root></app-root> </body> </html>
{ "end_byte": 253, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/elements/src/index.html" }
angular/adev/src/content/examples/elements/src/main.ts_0_275
import {bootstrapApplication, provideProtractorTestingSupport} from '@angular/platform-browser'; import {AppComponent} from './app/app.component'; bootstrapApplication(AppComponent, { providers: [provideProtractorTestingSupport()], }).catch((err) => console.error(err));
{ "end_byte": 275, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/elements/src/main.ts" }
angular/adev/src/content/examples/elements/src/app/popup.service.ts_0_1769
import {ApplicationRef, createComponent, EnvironmentInjector, Injectable} from '@angular/core'; import {NgElement, WithProperties} from '@angular/elements'; import {PopupComponent} from './popup.component'; @Injectable() export class PopupService { constructor( private injector: EnvironmentInjector, private applicationRef: ApplicationRef, ) {} // Previous dynamic-loading method required you to set up infrastructure // before adding the popup to the DOM. showAsComponent(message: string) { // Create element const popup = document.createElement('popup-component'); // Create the component and wire it up with the element const popupComponentRef = createComponent(PopupComponent, { environmentInjector: this.injector, hostElement: popup, }); // Attach to the view so that the change detector knows to run this.applicationRef.attachView(popupComponentRef.hostView); // Listen to the close event popupComponentRef.instance.closed.subscribe(() => { document.body.removeChild(popup); this.applicationRef.detachView(popupComponentRef.hostView); }); // Set the message popupComponentRef.instance.message = message; // Add to the DOM document.body.appendChild(popup); } // This uses the new custom-element method to add the popup to the DOM. showAsElement(message: string) { // Create element const popupEl: NgElement & WithProperties<PopupComponent> = document.createElement( 'popup-element', ) as any; // Listen to the close event popupEl.addEventListener('closed', () => document.body.removeChild(popupEl)); // Set the message popupEl.message = message; // Add to the DOM document.body.appendChild(popupEl); } }
{ "end_byte": 1769, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/elements/src/app/popup.service.ts" }
angular/adev/src/content/examples/elements/src/app/popup.component.ts_0_1359
// #docregion import {Component, EventEmitter, HostBinding, Input, Output} from '@angular/core'; import {animate, state, style, transition, trigger} from '@angular/animations'; @Component({ standalone: true, selector: 'my-popup', template: ` <span>Popup: {{ message }}</span> <button type="button" (click)="closed.next()">&#x2716;</button> `, animations: [ trigger('state', [ state('opened', style({transform: 'translateY(0%)'})), state('void, closed', style({transform: 'translateY(100%)', opacity: 0})), transition('* => *', animate('100ms ease-in')), ]), ], styles: [ ` :host { position: absolute; bottom: 0; left: 0; right: 0; background: #009cff; height: 48px; padding: 16px; display: flex; justify-content: space-between; align-items: center; border-top: 1px solid black; font-size: 24px; } button { border-radius: 50%; } `, ], }) export class PopupComponent { @HostBinding('@state') state: 'opened' | 'closed' = 'closed'; @Input() get message(): string { return this._message; } set message(message: string) { this._message = message; this.state = 'opened'; } private _message = ''; @Output() closed = new EventEmitter<void>(); }
{ "end_byte": 1359, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/elements/src/app/popup.component.ts" }
angular/adev/src/content/examples/elements/src/app/app.component.ts_0_918
import {Component, Injector} from '@angular/core'; import {createCustomElement} from '@angular/elements'; import {PopupComponent} from './popup.component'; import {PopupService} from './popup.service'; @Component({ standalone: true, selector: 'app-root', template: ` <input #input value="Message" /> <button type="button" (click)="popup.showAsComponent(input.value)">Show as component</button> <button type="button" (click)="popup.showAsElement(input.value)">Show as element</button> `, providers: [PopupService], imports: [PopupComponent], }) export class AppComponent { constructor( injector: Injector, public popup: PopupService, ) { // Convert `PopupComponent` to a custom element. const PopupElement = createCustomElement(PopupComponent, {injector}); // Register the custom element with the browser. customElements.define('popup-element', PopupElement); } }
{ "end_byte": 918, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/elements/src/app/app.component.ts" }
angular/adev/src/content/examples/styleguide/BUILD.bazel_0_3300
package(default_visibility = ["//visibility:public"]) exports_files([ "src/01-01/app/app.component.ts", "src/01-01/app/app.module.ts", "src/01-01/app/heroes/hero.component.avoid.ts", "src/01-01/app/heroes/heroes.component.ts", "src/01-01/app/heroes/shared/hero.model.ts", "src/01-01/app/heroes/shared/hero.service.ts", "src/01-01/app/heroes/shared/mock-heroes.ts", "src/01-01/main.ts", "src/02-05/main.ts", "src/02-07/app/heroes/hero.component.avoid.ts", "src/02-07/app/heroes/hero.component.ts", "src/02-07/app/users/users.component.avoid.ts", "src/02-07/app/users/users.component.ts", "src/02-08/app/shared/validate.directive.avoid.ts", "src/02-08/app/shared/validate.directive.ts", "src/04-08/app/app.module.ts", "src/04-10/app/heroes/heroes.component.html", "src/04-10/app/heroes/heroes.component.ts", "src/04-10/app/shared/filter-text/filter-text.component.ts", "src/04-10/app/shared/filter-text/filter-text.service.ts", "src/04-10/app/shared/init-caps.pipe.ts", "src/04-10/app/shared/shared.module.ts", "src/05-02/app/app.component.html", "src/05-02/app/heroes/shared/hero-button/hero-button.component.avoid.ts", "src/05-02/app/heroes/shared/hero-button/hero-button.component.ts", "src/05-03/app/app.component.avoid.html", "src/05-03/app/app.component.html", "src/05-03/app/heroes/shared/hero-button/hero-button.component.avoid.ts", "src/05-03/app/heroes/shared/hero-button/hero-button.component.ts", "src/05-04/app/heroes/heroes.component.avoid.ts", "src/05-04/app/heroes/heroes.component.css", "src/05-04/app/heroes/heroes.component.html", "src/05-04/app/heroes/heroes.component.ts", "src/05-12/app/heroes/shared/hero-button/hero-button.component.avoid.ts", "src/05-12/app/heroes/shared/hero-button/hero-button.component.ts", "src/05-13/app/app.component.avoid.html", "src/05-13/app/app.component.html", "src/05-13/app/heroes/shared/hero-button/hero-button.component.avoid.ts", "src/05-13/app/heroes/shared/hero-button/hero-button.component.ts", "src/05-13/app/heroes/shared/hero-highlight.directive.ts", "src/05-15/app/heroes/hero-list/hero-list.component.avoid.ts", "src/05-15/app/heroes/hero-list/hero-list.component.ts", "src/05-16/app/app.component.avoid.html", "src/05-16/app/app.component.html", "src/05-16/app/heroes/hero.component.avoid.ts", "src/05-16/app/heroes/hero.component.ts", "src/05-17/app/heroes/hero-list/hero-list.component.avoid.ts", "src/05-17/app/heroes/hero-list/hero-list.component.ts", "src/05-18/app/heroes/hero/hero.component.avoid.ts", "src/05-18/app/heroes/hero/hero.component.optional.ts", "src/05-18/app/heroes/hero/hero.component.ts", "src/06-01/app/app.component.html", "src/06-01/app/shared/highlight.directive.ts", "src/06-03/app/shared/validator.directive.ts", "src/06-03/app/shared/validator2.directive.ts", "src/07-01/app/heroes/shared/hero.service.ts", "src/07-04/app/heroes/shared/hero-arena.service.avoid.ts", "src/07-04/app/heroes/shared/hero-arena.service.ts", "src/09-01/app/heroes/shared/hero-button/hero-button.component.avoid.ts", "src/09-01/app/heroes/shared/hero-button/hero-button.component.ts", ])
{ "end_byte": 3300, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/styleguide/BUILD.bazel" }
angular/adev/src/content/examples/styleguide/e2e/src/app.e2e-spec.ts_0_4111
import {browser, element, by} from 'protractor'; describe('Style Guide', () => { it('01-01', async () => { await browser.get('#/01-01'); const pre = element(by.tagName('toh-heroes > pre')); expect(await pre.getText()).toContain('Bombasto'); expect(await pre.getText()).toContain('Tornado'); expect(await pre.getText()).toContain('Magneta'); }); it('02-07', async () => { await browser.get('#/02-07'); const hero = element(by.tagName('toh-hero > div')); const users = element(by.tagName('admin-users > div')); expect(await hero.getText()).toBe('hero component'); expect(await users.getText()).toBe('users component'); }); it('02-08', async () => { await browser.get('#/02-08'); const input = element(by.tagName('input[tohvalidate]')); expect(await input.isPresent()).toBe(true); }); it('04-10', async () => { await browser.get('#/04-10'); const div = element(by.tagName('sg-app > toh-heroes > div')); expect(await div.getText()).toBe('This is heroes component'); }); it('05-02', async () => { await browser.get('#/05-02'); const button = element(by.tagName('sg-app > toh-hero-button > button')); expect(await button.getText()).toBe('Hero button'); }); it('05-03', async () => { await browser.get('#/05-03'); const button = element(by.tagName('sg-app > toh-hero-button > button')); expect(await button.getText()).toBe('Hero button'); }); it('05-04', async () => { await browser.get('#/05-04'); const h2 = element(by.tagName('sg-app > toh-heroes > div > h2')); expect(await h2.getText()).toBe('My Heroes'); }); it('05-12', async () => { await browser.get('#/05-12'); const button = element(by.tagName('sg-app > toh-hero-button > button')); expect(await button.getText()).toBe('OK'); }); it('05-13', async () => { await browser.get('#/05-13'); const button = element(by.tagName('sg-app > toh-hero-button > button')); expect(await button.getText()).toBe('OK'); }); it('05-14', async () => { await browser.get('#/05-14'); const toast = element(by.tagName('sg-app > toh-toast')); expect(await toast.getText()).toBe('...'); }); it('05-15', async () => { await browser.get('#/05-15'); const heroList = element(by.tagName('sg-app > toh-hero-list')); expect(await heroList.getText()).toBe('...'); }); it('05-16', async () => { await browser.get('#/05-16'); const hero = element(by.tagName('sg-app > toh-hero')); expect(await hero.getText()).toBe('...'); }); it('05-17', async () => { await browser.get('#/05-17'); const section = element(by.tagName('sg-app > toh-hero-list > section')); expect(await section.getText()).toContain('Our list of heroes'); expect(await section.getText()).toContain('Total powers'); expect(await section.getText()).toContain('Average power'); }); it('06-01', async () => { await browser.get('#/06-01'); const div = element(by.tagName('sg-app > div[tohhighlight]')); expect(await div.getText()).toBe('Bombasta'); }); it('06-03', async () => { await browser.get('#/06-03'); const input = element(by.tagName('input[tohvalidator]')); expect(await input.isPresent()).toBe(true); }); // temporarily disabled because of a weird issue when used with rxjs v6 with rxjs-compat xit('07-01', async () => { await browser.get('#/07-01'); const lis = element.all(by.tagName('sg-app > ul > li')); expect(await lis.get(0).getText()).toBe('Windstorm'); expect(await lis.get(1).getText()).toBe('Bombasto'); expect(await lis.get(2).getText()).toBe('Magneta'); expect(await lis.get(3).getText()).toBe('Tornado'); }); it('07-04', async () => { await browser.get('#/07-04'); const pre = element(by.tagName('toh-app > pre')); expect(await pre.getText()).toContain('[]'); }); it('09-01', async () => { await browser.get('#/09-01'); const button = element(by.tagName('sg-app > toh-hero-button > button')); expect(await button.getText()).toBe('OK'); }); });
{ "end_byte": 4111, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/styleguide/e2e/src/app.e2e-spec.ts" }
angular/adev/src/content/examples/styleguide/src/index.html_0_309
<!DOCTYPE html> <!-- #docregion --> <html lang="en"> <head> <base href="/"> <title>Style Guide Sample</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <app-root></app-root> </body> </html> <!-- #enddocregion -->
{ "end_byte": 309, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/styleguide/src/index.html" }