Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion aio/content/examples/testing/specs.stackblitz.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"description": "Testing - app.specs",
"description": "Testing - specs",
"files":[
"src/styles.css",

Expand Down
5 changes: 0 additions & 5 deletions aio/content/examples/testing/src/app/1st.spec.ts

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';

import { AboutComponent } from './about.component';
import { HighlightDirective } from './shared/highlight.directive';
import { HighlightDirective } from '../shared/highlight.directive';

let fixture: ComponentFixture<AboutComponent>;

Expand All @@ -19,8 +18,8 @@ describe('AboutComponent (highlightDirective)', () => {
});

it('should have skyblue <h2>', () => {
const de = fixture.debugElement.query(By.css('h2'));
const bgColor = de.nativeElement.style.backgroundColor;
const h2: HTMLElement = fixture.nativeElement.querySelector('h2');
const bgColor = h2.style.backgroundColor;
expect(bgColor).toBe('skyblue');
});
// #enddocregion tests
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ import { Component } from '@angular/core';
@Component({
template: `
<h2 highlight="skyblue">About</h2>
<h3>Quote of the day:</h3>
<twain-quote></twain-quote>
<p>All about this sample</p>`
`
})
export class AboutComponent { }
76 changes: 76 additions & 0 deletions aio/content/examples/testing/src/app/app-initial.component.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
// #docplaster
// #docregion
import { TestBed, async } from '@angular/core/testing';
// #enddocregion
import { AppComponent } from './app-initial.component';
/*
// #docregion
import { AppComponent } from './app.component';

describe('AppComponent', () => {
// #enddocregion
*/
describe('AppComponent (initial CLI version)', () => {
// #docregion
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent
],
}).compileComponents();
}));
it('should create the app', async(() => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app).toBeTruthy();
}));
it(`should have as title 'app'`, async(() => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app.title).toEqual('app');
}));
it('should render title in a h1 tag', async(() => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.nativeElement;
expect(compiled.querySelector('h1').textContent).toContain('Welcome to app!');
}));
});
// #enddocregion

/// As it should be
import { DebugElement } from '@angular/core';
import { ComponentFixture } from '@angular/core/testing';

describe('AppComponent (initial CLI version - as it should be)', () => {

let app: AppComponent;
let de: DebugElement;
let fixture: ComponentFixture<AppComponent>;

beforeEach(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent
],
});

fixture = TestBed.createComponent(AppComponent);
app = fixture.componentInstance;
de = fixture.debugElement;
});

it('should create the app', () => {
expect(app).toBeDefined();
});

it(`should have as title 'app'`, () => {
expect(app.title).toEqual('app');
});

it('should render title in an h1 tag', () => {
fixture.detectChanges();
expect(de.nativeElement.querySelector('h1').textContent)
.toContain('Welcome to app!');
});
});
11 changes: 11 additions & 0 deletions aio/content/examples/testing/src/app/app-initial.component.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// #docregion
// Reduced version of the initial AppComponent generated by CLI
import { Component } from '@angular/core';

@Component({
selector: 'app-root',
template: '<h1>Welcome to {{title}}!</h1>'
})
export class AppComponent {
title = 'app';
}
2 changes: 1 addition & 1 deletion aio/content/examples/testing/src/app/app-routing.module.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';

import { AboutComponent } from './about.component';
import { AboutComponent } from './about/about.component';

@NgModule({
imports: [
Expand Down
4 changes: 2 additions & 2 deletions aio/content/examples/testing/src/app/app.component.html
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
<!-- #docregion -->
<app-banner></app-banner>
<app-welcome></app-welcome>

<!-- #docregion links -->
<nav>
<a routerLink="/dashboard">Dashboard</a>
<a routerLink="/heroes">Heroes</a>
<a routerLink="/about">About</a>
</nav>

<!-- #enddocregion links -->
<router-outlet></router-outlet>
65 changes: 29 additions & 36 deletions aio/content/examples/testing/src/app/app.component.router.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@
import { async, ComponentFixture, fakeAsync, TestBed, tick,
} from '@angular/core/testing';

import { asyncData } from '../testing';

import { RouterTestingModule } from '@angular/router/testing';
import { SpyLocation } from '@angular/common/testing';

import { click } from '../testing';

// r - for relatively obscure router symbols
import * as r from '@angular/router';
import { Router, RouterLinkWithHref } from '@angular/router';
Expand All @@ -17,11 +17,15 @@ import { By } from '@angular/platform-browser';
import { DebugElement, Type } from '@angular/core';
import { Location } from '@angular/common';

import { click } from '../testing';

import { AppModule } from './app.module';
import { AppComponent } from './app.component';
import { AboutComponent } from './about.component';
import { AboutComponent } from './about/about.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { TwainService } from './shared/twain.service';
import { TwainService } from './twain/twain.service';

import { HeroService, TestHeroService } from './model/testing/test-hero.service';

let comp: AppComponent;
let fixture: ComponentFixture<AppComponent>;
Expand All @@ -31,15 +35,19 @@ let location: SpyLocation;

describe('AppComponent & RouterTestingModule', () => {

beforeEach( async(() => {
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [ AppModule, RouterTestingModule ]
imports: [ AppModule, RouterTestingModule ],
providers: [
{ provide: HeroService, useClass: TestHeroService }
]
})
.compileComponents();
}));

it('should navigate to "Dashboard" immediately', fakeAsync(() => {
createComponent();
tick(); // wait for async data to arrive
expect(location.path()).toEqual('/dashboard', 'after initialNavigation()');
expectElementOf(DashboardComponent);
}));
Expand All @@ -64,7 +72,7 @@ describe('AppComponent & RouterTestingModule', () => {
}));

// Can't navigate to lazy loaded modules with this technique
xit('should navigate to "Heroes" on click', fakeAsync(() => {
xit('should navigate to "Heroes" on click (not working yet)', fakeAsync(() => {
createComponent();
page.heroesLinkDe.nativeElement.click();
advance();
Expand All @@ -84,9 +92,9 @@ import { HeroListComponent } from './hero/hero-list.component';
let loader: SpyNgModuleFactoryLoader;

///////// Can't get lazy loaded Heroes to work yet
xdescribe('AppComponent & Lazy Loading', () => {
xdescribe('AppComponent & Lazy Loading (not working yet)', () => {

beforeEach( async(() => {
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [ AppModule, RouterTestingModule ]
})
Expand All @@ -95,40 +103,36 @@ xdescribe('AppComponent & Lazy Loading', () => {

beforeEach(fakeAsync(() => {
createComponent();
loader = TestBed.get(NgModuleFactoryLoader);
loader.stubbedModules = {expected: HeroModule};
loader = TestBed.get(NgModuleFactoryLoader);
loader.stubbedModules = { expected: HeroModule };
router.resetConfig([{path: 'heroes', loadChildren: 'expected'}]);
}));

it('dummy', () => expect(true).toBe(true) );


it('should navigate to "Heroes" on click', async(() => {
page.heroesLinkDe.nativeElement.click();
advance();
expectPathToBe('/heroes');
expectElementOf(HeroListComponent);
}));

xit('can navigate to "Heroes" w/ browser location URL change', fakeAsync(() => {
it('can navigate to "Heroes" w/ browser location URL change', fakeAsync(() => {
location.go('/heroes');
advance();
expectPathToBe('/heroes');
expectElementOf(HeroListComponent);

page.expectEvents([
[r.NavigationStart, '/heroes'], [r.RoutesRecognized, '/heroes'],
[r.NavigationEnd, '/heroes']
]);
}));
});

////// Helpers /////////

/** Wait a tick, then detect changes */
/**
* Advance to the routed page
* Wait a tick, then detect changes, and tick again
*/
function advance(): void {
tick();
fixture.detectChanges();
tick(); // wait while navigating
fixture.detectChanges(); // update view
tick(); // wait for async data to arrive
}

function createComponent() {
Expand All @@ -140,8 +144,8 @@ function createComponent() {
router = injector.get(Router);
router.initialNavigation();
spyOn(injector.get(TwainService), 'getQuote')
.and.returnValue(Promise.resolve('Test Quote')); // fakes it

// fake fast async observable
.and.returnValue(asyncData('Test Quote'));
advance();

page = new Page();
Expand All @@ -151,25 +155,14 @@ class Page {
aboutLinkDe: DebugElement;
dashboardLinkDe: DebugElement;
heroesLinkDe: DebugElement;
recordedEvents: any[] = [];

// for debugging
comp: AppComponent;
location: SpyLocation;
router: Router;
fixture: ComponentFixture<AppComponent>;

expectEvents(pairs: any[]) {
const events = this.recordedEvents;
expect(events.length).toEqual(pairs.length, 'actual/expected events length mismatch');
for (let i = 0; i < events.length; ++i) {
expect((<any>events[i].constructor).name).toBe(pairs[i][0].name, 'unexpected event name');
expect((<any>events[i]).url).toBe(pairs[i][1], 'unexpected event url');
}
}

constructor() {
router.events.subscribe(e => this.recordedEvents.push(e));
const links = fixture.debugElement.queryAll(By.directive(RouterLinkWithHref));
this.aboutLinkDe = links[2];
this.dashboardLinkDe = links[0];
Expand Down
Loading