Skip to content

Instantly share code, notes, and snippets.

@ysyun
Created July 4, 2016 09:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ysyun/d0d2ebfb6dafe1b285c2d3adcf7ef4d6 to your computer and use it in GitHub Desktop.
Save ysyun/d0d2ebfb6dafe1b285c2d3adcf7ef4d6 to your computer and use it in GitHub Desktop.
Angular2 + Typescript + Jasmine Test with Child Component Override
<!DOCTYPE html>
<html>
<head>
<title>Angular2 Testing Playground - Jasmine</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.4.1/jasmine.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.4.1/jasmine.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.4.1/jasmine-html.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.4.1/boot.js"></script>
<script src="https://code.angularjs.org/tools/system.js"></script>
<script src="https://code.angularjs.org/tools/typescript.js"></script>
<script src="https://code.angularjs.org/2.0.0-beta.8/angular2-polyfills.js"></script>
<script src="https://code.angularjs.org/2.0.0-beta.8/Rx.js"></script>
<script src="https://code.angularjs.org/2.0.0-beta.8/angular2.js"></script>
<script src="https://code.angularjs.org/2.0.0-beta.8/http.js"></script>
<script src="https://code.angularjs.org/2.0.0-beta.8/testing.dev.js"></script>
</head>
<body>
<script>
System.config({
transpiler: 'typescript',
typescriptOptions: {emitDecoratorMetadata: true},
packages: {'src': {defaultExtension: 'ts'}}
});
Promise.all([
System.import('test/my-http.service.spec.ts'),
System.import('test/my.component.spec.ts')
])
.then(window.onload)
.catch(console.error.bind(console));
</script>
</body>
</html>
import {Injectable} from 'angular2/core';
import {Http} from 'angular2/http';
import 'rxjs/add/operator/map'; //what the hell is this?
@Injectable() // do not forget ()
export class MyHttpService { // do not forget 'export'
constructor(public http: Http) {
console.log('MyHttpService is instantiated');
}
get(req) {
return this.http.get('https://my.some.remote.server/some/'+req)
.map(res => res.json());
}
doSomething() {
return 'done';
}
}
import {Component} from 'angular2/core';
@Component({
selector: 'my-navbar',
template: '<div>NAV BAR</div>'
})
export class MyNavbarComponent {}
import {Component} from 'angular2/core';
@Component({
selector: 'my-toolbar',
template: '<div>TOOL BAR</div>'
})
export class MyToolbarComponent {}
import {Component} from 'angular2/core';
import {MyNavbarComponent} from './my-navbar.component';
import {MyToolbarComponent} from './my-toolbar.component';
@Component({
selector: 'my-app',
template: `
<my-toolbar></my-toolbar>
{{foo}}
<my-navbar></my-navbar>
`,
directives: [MyNavbarComponent, MyToolbarComponent]
})
export class MyComponent {
constructor()
{
var myArray: IStringArray;
myArray = ['Bob', 'Fred'];
console.log('xxxxxxxxxxxxxxxxxxxx', myArray.length);
}
}
interface IStringArray {
[index: number]: string;
length: number;
}
<h1>Hello World!</h1>
//Using Angular version 2.0.0-beta.8
import {Component, provide, Injector} from 'angular2/core';
import {inject, describe, expect, it, beforeEachProviders} from 'angular2/testing';
import {XHRBackend, HTTP_PROVIDERS, Response, ResponseOptions} from 'angular2/http';
import {MockBackend} from 'angular2/http/testing';
//for component test
import {Component} from 'angular2/core';
import {injectAsync, TestComponentBuilder} from 'angular2/testing';
import {MyHttpService} from '../src/my-http-service';
describe('http-test', () => {
let xhrBackend, myHttpService;
beforeEach(() => {
injector = Injector.resolveAndCreate([
HTTP_PROVIDERS,
provide(XHRBackend, {useClass: MockBackend}),
MyHttpService
]);
xhrBackend = injector.get(XHRBackend);
myHttpService = injector.get(MyHttpService);
responseMap = {
'request1.json': {body: {foo: 'response1'}},
'request2.json': {body: {foo: 'response2'}}
}
xhrBackend.connections.subscribe(connection => {
for (var key in responseMap) {
if (connection.request.url.match(new RegExp(key))) {
connection.mockRespond(new Response(
new ResponseOptions(responseMap[key]))
);
}
}
});
]);
it('should respond with response1', () => {
myHttpService.get('request1.json').subscribe(response => {
expect(response.foo).toBe('response1');
});
});
it('should respond with response2', () => {
myHttpService.get('request2.json').subscribe(response => {
expect(response.foo).toBe('response2');
});
});
it('should return non observables', () => {
let result = myHttpService.doSomething();
expect(result).toBe('done');
});
});
// To run tests in the browser, need to include DOM adapters
import {setBaseTestProviders} from 'angular2/testing';
import {
TEST_BROWSER_PLATFORM_PROVIDERS,
TEST_BROWSER_APPLICATION_PROVIDERS
} from 'angular2/platform/testing/browser';
setBaseTestProviders(
TEST_BROWSER_PLATFORM_PROVIDERS,
TEST_BROWSER_APPLICATION_PROVIDERS
);
// import
import {
AsyncTestCompleter,
TestComponentBuilder,
beforeEachProviders,
beforeEach,
describe,
el,
expect,
injectAsync,
it
} from 'angular2/testing';
import {DOM} from 'angular2/src/platform/dom/dom_adapter';
import {Component, provide} from 'angular2/core';
import {ElementRef} from 'angular2/src/core/linker/element_ref';
import {MyComponent} from '../src/my.component';
import {MyNavbarComponent} from '../src/my-navbar.component';
import {MyToolbarComponent} from '../src/my-toolbar.component';
@Component({template:''})
class EmptyComponent() {}
describe('MyComponent', () => {
beforeEach(injectAsync([TestComponentBuilder], (tcb) => {
return tcb
.overrideDirective(MyComponent, MyNavbarComponent, EmptyComponent)
.overrideDirective(MyComponent, MyToolbarComponent, EmptyComponent)
.createAsync(MyComponent)
.then((componentFixture: ComponentFixture) => {
this.fixture = componentFixture;
});
));
it('should bind to {{foo}}', () => {
let el = this.fixture.nativeElement;
let myComponent = fixture.componentInstance;
myComponent.foo = 'FOO';
fixture.detectChanges();
expect(el.innerHTML).toMatch('FOO');
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment