<!DOCTYPE html>
<html>
<head>
<base href="." />
<title>Angular2 Playground</title>
<!-- Jasmine dependencies -->
<link data-require="jasmine@2.4.1" data-semver="2.4.1" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.4.1/jasmine.css" />
<script data-require="jasmine@2.4.1" data-semver="2.4.1" src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.4.1/jasmine.js"></script>
<script data-require="jasmine@2.4.1" data-semver="2.4.1" src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.4.1/jasmine-html.js"></script>
<script data-require="jasmine@2.4.1" data-semver="2.4.1" src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.4.1/boot.js"></script>
<!-- Angular 2 dependencies -->
<script src="https://unpkg.com/zone.js/dist/zone.js"></script>
<script src="https://unpkg.com/zone.js/dist/long-stack-trace-zone.js"></script>
<script src="https://unpkg.com/zone.js/dist/proxy.js?main=browser"></script>
<script src="https://unpkg.com/zone.js/dist/sync-test.js?main=browser"></script>
<script src="https://unpkg.com/zone.js/dist/jasmine-patch.js?main=browser"></script>
<script src="https://unpkg.com/zone.js@0.6.25/dist/async-test.js"></script>
<script src="https://unpkg.com/zone.js/dist/fake-async-test.js?main=browser"></script>
<script src="https://unpkg.com/reflect-metadata@0.1.3/Reflect.js"></script>
<script src="https://unpkg.com/systemjs@0.19.31/dist/system.js"></script>
<script src="config.js"></script>
<script>
//load all dependencies at the same time
Promise.all([
//required to test on browser
System.import('src/setup.spec'),
//specs
System.import('src/languagesService.spec'),
System.import('src/languagesServiceHttp.spec'),
System.import('src/capitalisePipe.spec'),
System.import('src/counter.spec'),
System.import('src/greeter.spec'),
System.import('src/logClicksDirective.spec'),
System.import('src/languagesServiceMockBackend.spec'),
System.import('src/router.spec'),
System.import('src/observables.spec')
]).then(function(modules) {
//manually trigger Jasmine test-runner
dispatchEvent(new Event('load'));
}).catch(console.error.bind(console));
</script>
<link rel="stylesheet" href="style.css" />
</head>
<body></body>
</html>
/* Styles go here */
System.config({
//use typescript for compilation
transpiler: 'typescript',
//typescript compiler options
typescriptOptions: {
emitDecoratorMetadata: true
},
paths: {
'npm:': 'https://unpkg.com/'
},
//map tells the System loader where to look for things
map: {
'app': './src',
'@angular/core': 'npm:@angular/core/bundles/core.umd.js',
'@angular/common': 'npm:@angular/common/bundles/common.umd.js',
'@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
'@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
'@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
'@angular/http': 'npm:@angular/http/bundles/http.umd.js',
'@angular/router': 'npm:@angular/router/bundles/router.umd.js',
'@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
'@angular/core/testing': 'npm:@angular/core/bundles/core-testing.umd.js',
'@angular/common/testing': 'npm:@angular/common/bundles/common-testing.umd.js',
'@angular/compiler/testing': 'npm:@angular/compiler/bundles/compiler-testing.umd.js',
'@angular/platform-browser/testing': 'npm:@angular/platform-browser/bundles/platform-browser-testing.umd.js',
'@angular/platform-browser-dynamic/testing': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic-testing.umd.js',
'@angular/http/testing': 'npm:@angular/http/bundles/http-testing.umd.js',
'@angular/router/testing': 'npm:@angular/router/bundles/router-testing.umd.js',
'rxjs': 'npm:rxjs@5.4.3',
'typescript': 'npm:typescript@2.0.2/lib/typescript.js'
},
//packages defines our app package
packages: {
app: {
main: './main.ts',
defaultExtension: 'ts'
},
rxjs: {
defaultExtension: 'js'
}
}
});
//main entry point
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {AppModule} from './app';
platformBrowserDynamic().bootstrapModule(AppModule)
//our root app component
import {Component, NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
@Component({
selector: 'my-app',
template: `
<div>
<h2>Hello {{name}}</h2>
</div>
`,
})
export class App {
name:string;
constructor() {
this.name = 'Angular2'
}
}
@NgModule({
imports: [ BrowserModule ],
declarations: [ App ],
bootstrap: [ App ]
})
export class AppModule {}
import {TestBed} from '@angular/core/testing';
import {BrowserDynamicTestingModule, platformBrowserDynamicTesting} from '@angular/platform-browser-dynamic/testing';
TestBed.initTestEnvironment(
BrowserDynamicTestingModule,
platformBrowserDynamicTesting()
);
//a simple service
import {Injectable} from '@angular/core';
@Injectable()
export class LanguagesService {
get() {
return ['en', 'es', 'fr'];
}
}
import {inject, TestBed} from '@angular/core/testing';
import {LanguagesService} from './languagesService';
describe('Service: LanguagesService', () => {
let service;
beforeEach(() => TestBed.configureTestingModule({
providers: [ LanguagesService ]
}));
beforeEach(inject([LanguagesService], s => {
service = s;
}));
it('should return available languages', () => {
let languages = service.get();
expect(languages).toContain('en');
expect(languages).toContain('es');
expect(languages).toContain('fr');
expect(languages.length).toEqual(3);
});
});
import {Pipe, PipeTransform} from '@angular/core';
@Pipe({
name: 'capitalise'
})
export class CapitalisePipe implements PipeTransform {
transform(value: string): string {
if (typeof value !== 'string') {
throw new Error('Requires a String as input');
}
return value.toUpperCase();
}
}
import {inject, TestBed} from '@angular/core/testing';
import {CapitalisePipe} from './capitalisePipe';
describe('Pipe: CapitalisePipe', () => {
let pipe;
//setup
beforeEach(() => TestBed.configureTestingModule({
providers: [ CapitalisePipe ]
}));
beforeEach(inject([CapitalisePipe], p => {
pipe = p;
}));
//specs
it('should work with empty string', () => {
expect(pipe.transform('')).toEqual('');
//fail('something went wrong')
});
it('should capitalise', () => {
expect(pipe.transform('wow')).toEqual('WOW');
//pending('add more expectations')
});
it('should throw with invalid values', () => {
//must use arrow function for expect to capture exception
expect(()=>pipe.transform(undefined)).toThrow();
expect(()=>pipe.transform()).toThrow();
expect(()=>pipe.transform()).toThrowError('Requires a String as input');
});
})
import {Component, Input, Output, EventEmitter} from '@angular/core';
@Component({
selector: 'counter',
template: `
<div>
<h1>{{counter}}</h1>
<button (click)="change(1)">+1</button>
<button (click)="change(-1)">-1</button>
</div>`
})
export class Counter {
@Output() changes = new EventEmitter();
constructor(){
this.counter = 0;
}
change(increment) {
this.counter += increment;
//we use emit as next is marked as deprecated
this.changes.emit(this.counter);
}
}
import {inject, TestBed} from '@angular/core/testing';
import {Counter} from './counter';
import {async, fakeAsync, tick} from '@angular/core/testing';
/*
Usage: <counter (changes)="log($event)"></counter>
log($event) { console.log($event) }
*/
describe('EventEmitter: Counter', () => {
let counter;
//setup
beforeEach(() => TestBed.configureTestingModule({
providers: [ Counter ]
}));
beforeEach(inject([Counter], c => {
counter = c;
}))
//specs
it('should increment +1 (async)', async(() => {
counter.changes.subscribe(x => {
expect(x).toBe(1);
});
counter.change(1);
}));
it('should decrement -1 (async)', async(() => {
counter.changes.subscribe(x => {
expect(x).toBe(-1);
});
counter.change(-1);
}));
it('should increment +1 (fakeAsync/tick)', fakeAsync(() => {
counter.changes.subscribe(x => {
expect(x).toBe(1);
});
counter.change(1);
//execute all pending asynchronous calls
tick();
}));
it('should decrement -1 (fakeAsync/tick)', fakeAsync(() => {
counter.changes.subscribe(x => {
expect(x).toBe(-1);
});
counter.change(-1);
//execute all pending asynchronous calls
tick();
});
it('should increment +1 (done)', done => {
counter.changes.subscribe(x => {
expect(x).toBe(1);
done();
});
counter.change(1);
});
it('should decrement -1 (done)', done => {
counter.changes.subscribe(x => {
expect(x).toBe(-1);
done();
});
counter.change(-1);
});
})
import {Component, Input} from '@angular/core';
@Component({
selector: 'greeter',
template: `<h1>Hello {{name}}!</h1>`
})
export class Greeter {
@Input() name;
}
import {ComponentFixture, TestBed, async, fakeAsync, tick} from '@angular/core/testing';
import {Greeter} from './greeter';
import {By} from '@angular/platform-browser';
/*
Usage: <greeter name="Joe"></greeter>
Renders: <h1>Hello Joe!</h1>
*/
describe('Component: Greeter', () => {
let fixture, greeter, element, de;
//setup
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [ Greeter ]
});
fixture = TestBed.createComponent(Greeter);
greeter = fixture.componentInstance;
element = fixture.nativeElement;
de = fixture.debugElement;
});
//specs
it('should render `Hello World!` (async)', async(() => {
greeter.name = 'World';
//trigger change detection
fixture.detectChanges();
fixture.whenStable().then(() => {
expect(element.querySelector('h1').innerText).toBe('Hello World!');
expect(de.query(By.css('h1')).nativeElement.innerText).toBe('Hello World!');
});
}));
it('should render `Hello World!` (fakeAsync/tick)', fakeAsync(() => {
greeter.name = 'World';
//trigger change detection
fixture.detectChanges();
//execute all pending asynchronous calls
tick();
expect(element.querySelector('h1').innerText).toBe('Hello World!');
expect(de.query(By.css('h1')).nativeElement.innerText).toBe('Hello World!');
}));
it('should render `Hello World!` (done)', done => {
greeter.name = 'World';
//trigger change detection
fixture.detectChanges();
fixture.whenStable().then(() => {
expect(element.querySelector('h1').innerText).toBe('Hello World!');
expect(de.query(By.css('h1')).nativeElement.innerText).toBe('Hello World!');
done();
});
});
})
import {Observable} from 'rxjs/Rx';
import {async, fakeAsync, tick} from '@angular/core/testing';
describe('Observable: basic observable', () => {
var basic$;
//setup
beforeEach(() => {
basic$ = new Observable(observer => {
//pushing values
observer.next(1);
observer.next(2);
observer.next(3);
//complete stream
observer.complete();
});
});
//specs
it('should create the expected sequence (async)', async(() => {
let expected = [1,2,3],
index = 0;
basic$
.subscribe({
next: x => expect(x).toEqual(expected[index++]),
error: e => console.log(e)
});
}));
it('should create the expected sequence (fakeAsync/tick)', fakeAsync(() => {
let expected = [1,2,3],
index = 0;
basic$
.subscribe({
next: x => expect(x).toEqual(expected[index++]),
error: e => console.log(e)
});
//execute all pending asynchronous calls
tick();
}));
it('should create the expected sequence (done)', done => {
let expected = [1,2,3],
index = 0;
basic$
.subscribe({
next: x => expect(x).toEqual(expected[index++]),
error: e => console.log(e),
complete: () => done()
});
});
});
import {Directive, HostListener, Component, Output, EventEmitter} from '@angular/core';
@Directive({
selector: "[log-clicks]"
})
export class logClicks {
counter = 0;
@Output() changes = new EventEmitter();
@HostListener('click', ['$event.target'])
clicked(target) {
console.log(`Click on [${target}]: ${++this.counter}`);
//we use emit as next is marked as deprecated
this.changes.emit(this.counter);
}
}
import {ComponentFixture, TestBed, async, fakeAsync, tick} from '@angular/core/testing';
import {Component, Output, EventEmitter} from '@angular/core';
import {logClicks} from './logClicksDirective';
/*
Usage: <div log-clicks></div>
For each click increments the public property `counter`.
*/
@Component({
selector: 'container',
template: `<div log-clicks (changes)="changed($event)"></div>`,
directives: [logClicks]
})
export class Container {
@Output() changes = new EventEmitter();
changed(value){
this.changes.emit(value);
}
}
describe('Directive: logClicks', () => {
let fixture, container, element;
//setup
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [ Container, logClicks ]
});
fixture = TestBed.createComponent(Container);
container = fixture.componentInstance;
element = fixture.nativeElement;
});
//specs
it('should increment counter (async)', async(() => {
let div = element.querySelector('div');
//set up subscriber
container.changes.subscribe(x => {
expect(x).toBe(1);
});
//trigger click on container
div.click();
}));
it('should increment counter (fakeAsync/tick)', fakeAsync(() => {
let div = element.querySelector('div');
//set up subscriber
container.changes.subscribe(x => {
expect(x).toBe(1);
});
//trigger click on container
div.click();
//execute all pending asynchronous calls
tick();
}));
it('should increment counter (done)', done => {
let div = element.querySelector('div');
//set up subscriber
container.changes.subscribe(x => {
expect(x).toBe(1);
done();
});
//trigger click on container
div.click();
});
})
import {Injectable} from '@angular/core';
import {Http} from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class LanguagesServiceHttp {
constructor(private http:Http) { }
get(){
return this.http.get('api/languages.json')
.map(response => response.json());
}
}
import {inject, TestBed, async, fakeAsync, tick} from '@angular/core/testing';
import {HttpModule} from '@angular/http';
import {LanguagesServiceHttp} from './languagesServiceHttp';
describe('Service: LanguagesServiceHttp', () => {
let service;
//setup
beforeEach(() => TestBed.configureTestingModule({
imports: [ HttpModule ],
providers: [ LanguagesServiceHttp ]
}));
beforeEach(inject([LanguagesServiceHttp], s => {
service = s;
}));
//specs
it('should return available languages (async)', async(() => {
service.get().subscribe(x => {
expect(x).toContain('en');
expect(x).toContain('es');
expect(x).toContain('fr');
expect(x.length).toEqual(3);
});
}));
// Note: can't use fakeAsync with XHR calls
it('should return available languages (done)', done => {
service.get().subscribe(x => {
expect(x).toContain('en');
expect(x).toContain('es');
expect(x).toContain('fr');
expect(x.length).toEqual(3);
done();
});
});
})
["en", "es", "fr"]
import {inject, TestBed, async} from '@angular/core/testing';
import {MockBackend} from '@angular/http/testing';
import {HttpModule, XHRBackend, Response, ResponseOptions} from '@angular/http';
import {LanguagesServiceHttp} from './languagesServiceHttp';
describe('MockBackend: LanguagesServiceHttp', () => {
let mockbackend, service;
//setup
beforeEach(() => {
TestBed.configureTestingModule({
imports: [ HttpModule ],
providers: [
LanguagesServiceHttp,
{ provide: XHRBackend, useClass: MockBackend }
]
})
});
beforeEach(inject([LanguagesServiceHttp, XHRBackend], (_service, _mockbackend) => {
service = _service;
mockbackend = _mockbackend;
}));
//specs
it('should return mocked response (async)', async(() => {
let response = ["ru", "es"];
mockbackend.connections.subscribe(connection => {
connection.mockRespond(new Response(new ResponseOptions({
body: JSON.stringify(response)
}));
});
service.get().subscribe(languages => {
expect(languages).toContain('ru');
expect(languages).toContain('es');
expect(languages.length).toBe(2);
});
}));
// Note: can't use fakeAsync with XHR calls
it('should return mocked response (done)', done => {
let response = ["ru", "es"];
mockbackend.connections.subscribe(connection => {
connection.mockRespond(new Response({body: JSON.stringify(response)}));
});
service.get().subscribe(languages => {
expect(languages).toContain('ru');
expect(languages).toContain('es');
expect(languages.length).toBe(2);
done();
});
});
})
import {TestBed, async, fakeAsync, tick, inject} from '@angular/core/testing';
import {Component, NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {Router, RouterModule, Routes} from '@angular/router';
import {RouterTestingModule} from '@angular/router/testing';
import {Location} from '@angular/common';
@Component({
selector: 'my-app',
template: `<router-outlet></router-outlet>`
})
class TestComponent { }
@Component({
selector: 'home',
template: `<h1>Home</h1>`
})
export class Home { }
export const routes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: Home },
{ path: '**', redirectTo: 'home' }
];
@NgModule({
imports: [
BrowserModule, RouterModule.forRoot(routes),
],
declarations: [TestComponent, Home],
bootstrap: [TestComponent],
exports: [TestComponent]
})
export class AppModule {}
describe('Router tests', () => {
let router;
//setup
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
AppModule
]
});
});
beforeEach(inject([Router], _router => {
router = _router;
});
it('default route redirects to home (fakeAsync/tick)', fakeAsync(() => {
let fixture = TestBed.createComponent(TestComponent);
router.initialNavigation(); // triggers default
fixture.detectChanges();
//execute all pending asynchronous calls
tick();
expect(location.pathname.endsWith('/home')).toBe(true);
}));
it('can navigate to home (fakeAsync/tick)', fakeAsync(() => {
let fixture = TestBed.createComponent(TestComponent);
router.navigate(['/home']);
fixture.detectChanges();
//execute all pending asynchronous calls
tick();
expect(location.pathname.endsWith('/home')).toBe(true);
}));
it('should redirect unexisting urls to Home (fakeAsync/tick)', fakeAsync(() => {
let fixture = TestBed.createComponent(TestComponent);
router.navigate(['/undefined/route']);
fixture.detectChanges();
//execute all pending asynchronous calls
tick();
expect(location.pathname.endsWith('/home')).toBe(true);
}));
});