Advanced Components. Components Testing....

21
IPT – Intellectual Products & Technologies http://www.iproduct.org/ Angular 2 and TypeScript Web Application Development Slide 1 Copyright © 2003-2017 IPT – Intellectual Products & Technologies Ltd. All rights reserved. Advanced Components. Components Testing. Ngrx Trayan Iliev IPT – Intellectual Products & Technologies e-mail: [email protected] web: http://www.iproduct.org Oracle®, Java™ and JavaScript™ are trademarks or registered trademarks of Oracle and/or its affiliates. Microsoft .NET, Visual Studio and Visual Studio Code are trademarks of Microsoft Corporation. Other names may be trademarks of their respective owners.

Transcript of Advanced Components. Components Testing....

Page 1: Advanced Components. Components Testing. Ngrxiproduct.org/wp-content/uploads/2017/04/Angular2_TypeScript_Iliev_2016_07.pdf · Testing Configuration with Webpack webpack.test.js –

IPT – Intellectual Products & Technologies http://www.iproduct.org/

Angular 2 and TypeScript Web Application Development

Slide 1Copyright © 2003-2017 IPT – Intellectual Products & Technologies Ltd. All rights reserved.

Advanced Components. Components Testing. Ngrx

Trayan Iliev

IPT – Intellectual Products & Technologiese-mail: [email protected]

web: http://www.iproduct.org

Oracle®, Java™ and JavaScript™ are trademarks or registered trademarks of Oracle and/or its affiliates.Microsoft .NET, Visual Studio and Visual Studio Code are trademarks of Microsoft Corporation.

Other names may be trademarks of their respective owners.

Page 2: Advanced Components. Components Testing. Ngrxiproduct.org/wp-content/uploads/2017/04/Angular2_TypeScript_Iliev_2016_07.pdf · Testing Configuration with Webpack webpack.test.js –

IPT – Intellectual Products & Technologies http://www.iproduct.org/

Angular 2 and TypeScript Web Application Development

Slide 2Copyright © 2003-2017 IPT – Intellectual Products & Technologies Ltd. All rights reserved.

Agenda I

1. Component interaction alternatives

2. Accessing component’s ViewChildren and ContentChildren using <ng-content>, @ViewChild, @ViewChildren, @ContentChild, @ContentChildren decorators.

3. Building custom attribute and structural directives using @HostListener, @HostBinding / @Input

4. Component lifecycle and use of custom lifecycle hooks: ngOnInit, ngOnChanges, ngDoCheck, ngOnDestroy, ngAfterContentInit, ngAfterContentChecked, ngAfterViewInit, ngAfterViewChecked

Page 3: Advanced Components. Components Testing. Ngrxiproduct.org/wp-content/uploads/2017/04/Angular2_TypeScript_Iliev_2016_07.pdf · Testing Configuration with Webpack webpack.test.js –

IPT – Intellectual Products & Technologies http://www.iproduct.org/

Angular 2 and TypeScript Web Application Development

Slide 3Copyright © 2003-2017 IPT – Intellectual Products & Technologies Ltd. All rights reserved.

Agenda II

6. Shadow DOM and Angular 2 view encapsulation modes – ViewEncapsulation.None, ViewEncapsulation.Emulated and ViewEncapsulation.Native

7. Test Driven Development (TDD) - unit testing Angular 2 classes and components using Jasmine and Karma

Page 4: Advanced Components. Components Testing. Ngrxiproduct.org/wp-content/uploads/2017/04/Angular2_TypeScript_Iliev_2016_07.pdf · Testing Configuration with Webpack webpack.test.js –

IPT – Intellectual Products & Technologies http://www.iproduct.org/

Angular 2 and TypeScript Web Application Development

Slide 4Copyright © 2003-2017 IPT – Intellectual Products & Technologies Ltd. All rights reserved.

Component Interaction Alternatives

Source: Angular 2 Cookbook: Component Interactionhttps://angular.io/docs/ts/latest/cookbook/component-communication.htmlLicense: CC BY 4.0.

Pass data from parent to child with input binding

Intercept input property changes with a setter

Intercept input property changes with ngOnChanges

Parent listens for child event

Parent interacts with child via a local variable

Parent calls a @ViewChild

Parent and children communicate via a service

Page 5: Advanced Components. Components Testing. Ngrxiproduct.org/wp-content/uploads/2017/04/Angular2_TypeScript_Iliev_2016_07.pdf · Testing Configuration with Webpack webpack.test.js –

IPT – Intellectual Products & Technologies http://www.iproduct.org/

Angular 2 and TypeScript Web Application Development

Slide 5Copyright © 2003-2017 IPT – Intellectual Products & Technologies Ltd. All rights reserved.

Angular 2 Services

Source: Angular 2 Developer Guide: Architecture overviewhttps://angular.io/docs/ts/latest/guide/architecture.htmlLicense: CC BY 4.0.

Page 6: Advanced Components. Components Testing. Ngrxiproduct.org/wp-content/uploads/2017/04/Angular2_TypeScript_Iliev_2016_07.pdf · Testing Configuration with Webpack webpack.test.js –

IPT – Intellectual Products & Technologies http://www.iproduct.org/

Angular 2 and TypeScript Web Application Development

Slide 6Copyright © 2003-2017 IPT – Intellectual Products & Technologies Ltd. All rights reserved.

Body content and template – two sources of markup / components / directives

Content projection using:<ng-content></ng-content><ng-content select=”header”></ng-content><ng-content select=”.css-class-select”></ng-content>

Accessing component’s ViewChildren and ContentChildren: @ViewChild(ComponentClass), @ViewChild('templVar')@ViewChildren(Item) items: QueryList<Item>;@ContentChild(Item) item: Item @ContentChildren(Item)items: QueryList<Item>;

Source: Rangle's Angular 2 Training Bookhttps://angular-2-training-book.rangle.io/handout/components/projection.htmlhttps://angular-2-training-book.rangle.io/handout/advanced-components/access_child_components.htmlLicense: Creative Commons Attribution-ShareAlike 4.0 International (CC BY-SA 4.0)

Component’s ViewChildren & ContentChildren

Page 7: Advanced Components. Components Testing. Ngrxiproduct.org/wp-content/uploads/2017/04/Angular2_TypeScript_Iliev_2016_07.pdf · Testing Configuration with Webpack webpack.test.js –

IPT – Intellectual Products & Technologies http://www.iproduct.org/

Angular 2 and TypeScript Web Application Development

Slide 7Copyright © 2003-2017 IPT – Intellectual Products & Technologies Ltd. All rights reserved.

@Directive

Directives add behaviour to an existing DOM element. One example use case for @Directive would be to add a highlight on mouse hover. Example – log-on-click.directive.ts :

import {Directive} from 'angular2/core';

@Directive({ selector: "[myLogOnClick]", host: { '(click)': 'onClick()' }})export class LogOnClickDirective { onClick() { console.log('Element clicked!'); }}

Page 8: Advanced Components. Components Testing. Ngrxiproduct.org/wp-content/uploads/2017/04/Angular2_TypeScript_Iliev_2016_07.pdf · Testing Configuration with Webpack webpack.test.js –

IPT – Intellectual Products & Technologies http://www.iproduct.org/

Angular 2 and TypeScript Web Application Development

Slide 8Copyright © 2003-2017 IPT – Intellectual Products & Technologies Ltd. All rights reserved.

Even Better @Directive

import {Directive, HostListener} from 'angular2/core';

@Directive({ selector: "[myLogOnClick]",})export class LogOnClickDirective { @HostListener('click') onClick() { console.log('Element clicked!'); }}

Prefer @HostListener and @HostBinding instead of the host property of the @Directive and @Component decorators

Page 9: Advanced Components. Components Testing. Ngrxiproduct.org/wp-content/uploads/2017/04/Angular2_TypeScript_Iliev_2016_07.pdf · Testing Configuration with Webpack webpack.test.js –

IPT – Intellectual Products & Technologies http://www.iproduct.org/

Angular 2 and TypeScript Web Application Development

Slide 9Copyright © 2003-2017 IPT – Intellectual Products & Technologies Ltd. All rights reserved.

Tooltip @Directive

import {Directive, HostListener, Input} from 'angular2/core';@Directive({ selector: '[myTooltip]', host: { '(mouseover)': 'show()' }})export class TooltipDirective { @Input('myTooltip') text: string; show() { alert(this.text); }}

<h1 myLogOnClick myTooltip="Enter new hero.">Hero Form</h1>

Page 10: Advanced Components. Components Testing. Ngrxiproduct.org/wp-content/uploads/2017/04/Angular2_TypeScript_Iliev_2016_07.pdf · Testing Configuration with Webpack webpack.test.js –

IPT – Intellectual Products & Technologies http://www.iproduct.org/

Angular 2 and TypeScript Web Application Development

Slide 10Copyright © 2003-2017 IPT – Intellectual Products & Technologies Ltd. All rights reserved.

Component Lifecycle and Lifecycle Hooks[https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html]

1. ngOnChanges – on input props change2. ngOnInit - after the first ngOnChanges3. ngDoCheck -every change detection run4. ngAfterContentInit - after first content proj.5. ngAfterContentChecked - each projection6. ngAfterViewInit - after first component's

views and child views initialization/check7. ngAfterViewChecked - each views check8. ngOnDestroy - before destroing

directive/component – should unsubscribe observables and detach event handlers

Source: Angular 2 Advanced Guide: Lifecycle Hookshttps://angular.io/docs/ts/latest/guide/lifecycle-hooks.htmlLicense: CC BY 4.0.

Page 11: Advanced Components. Components Testing. Ngrxiproduct.org/wp-content/uploads/2017/04/Angular2_TypeScript_Iliev_2016_07.pdf · Testing Configuration with Webpack webpack.test.js –

Slide 11

Angular 2 and TypeScript Web Application Development

IPT – Intellectual Products & Technologies http://www.iproduct.org/

Copyright © 2003-2017 IPT – Intellectual Products & Technologies Ltd. All rights reserved.

Web Components and Shadow DOM

4 emerging W3C specifications:Custom elements – provide a way for authors to build their own fully-featured DOM elements.

Shadow DOM – combining multiple DOM trees in one hierarchy[http://www.html5rocks.com/en/tutorials/webcomponents/shadowdom/]

Template – declare fragments of HTML that can be cloned and inserted in the document by script

HTML imports – <link rel="import" href="my-custom-cmp.html">

Page 12: Advanced Components. Components Testing. Ngrxiproduct.org/wp-content/uploads/2017/04/Angular2_TypeScript_Iliev_2016_07.pdf · Testing Configuration with Webpack webpack.test.js –

Slide 12

Angular 2 and TypeScript Web Application Development

IPT – Intellectual Products & Technologies http://www.iproduct.org/

Copyright © 2003-2017 IPT – Intellectual Products & Technologies Ltd. All rights reserved.

Using Shadow DOM – Example

<template id="custom-tag-tpl"> <style> h1 { color: blue; } </style> <h1>My Custom Component</h1></template>

var CustomCmpProto = Object.create(HTMLElement.prototype);CustomCmpProto.createdCallback = function() { var template = document.querySelector('#custom-tag-tpl'); var clone = document.importNode(template.content, true); this.createShadowRoot().appendChild(clone);};var MyCmp = document.registerElement('custom-cmp', {prototype: CustomCmpProto});document.body.appendChild(new MyCmp());

Page 13: Advanced Components. Components Testing. Ngrxiproduct.org/wp-content/uploads/2017/04/Angular2_TypeScript_Iliev_2016_07.pdf · Testing Configuration with Webpack webpack.test.js –

IPT – Intellectual Products & Technologies http://www.iproduct.org/

Angular 2 and TypeScript Web Application Development

Slide 13Copyright © 2003-2017 IPT – Intellectual Products & Technologies Ltd. All rights reserved.

Angular 2 View Encapsulation Modes

ViewEncapsulation.None – no specific measures are taken to isolate the component instances and avoid css style conflicts between components, component styles propagate to all other components ViewEncapsulation.Emulated (Default) – simulates Shadow DOM using custom attributes and component instance specific CSS attribute selectors to allow view encapsulationViewEncapsulation.Native – employ Shadow DOM if supported by browser – styles from Light HTML do not propagate to the component – Example:

@Component({…, encapsulation: ViewEncapsulation.Native,...})

Page 14: Advanced Components. Components Testing. Ngrxiproduct.org/wp-content/uploads/2017/04/Angular2_TypeScript_Iliev_2016_07.pdf · Testing Configuration with Webpack webpack.test.js –

IPT – Intellectual Products & Technologies http://www.iproduct.org/

Angular 2 and TypeScript Web Application Development

Slide 14Copyright © 2003-2017 IPT – Intellectual Products & Technologies Ltd. All rights reserved.

Test Driven Development (TDD) with Angular 2

Testing Angular 2 specific artefacts:

Classes,

Pipes,

Components / Directives

Services

Page 15: Advanced Components. Components Testing. Ngrxiproduct.org/wp-content/uploads/2017/04/Angular2_TypeScript_Iliev_2016_07.pdf · Testing Configuration with Webpack webpack.test.js –

IPT – Intellectual Products & Technologies http://www.iproduct.org/

Angular 2 and TypeScript Web Application Development

Slide 15Copyright © 2003-2017 IPT – Intellectual Products & Technologies Ltd. All rights reserved.

Example Testing Toolchain

Jasmine – the most popular core framework for writing Angular 2 unit tests Karma – test automation tool to control the tests execution:

In which browsers / DOM implementations to perform tests Allows to generate different type of reports about results

Phantom-js – headless DOM implementation JavaScript API allowing to bootstrap our Angular 2 application and run DOM specific tests.Istanbul – Karma uses it to generate test coverage reportsSinon – additional (optional) test spys, test subs, and mock XHR requests (Jasmine provides spyOn function)Chai - assertion library pairing with other testing frameworks

Source: Rangle's Angular 2 Training Bookhttps://angular-2-training-book.rangle.io/handout/testing/intro-to-tdd/toolchain.htmlLicense: Creative Commons Attribution-ShareAlike 4.0 International (CC BY-SA 4.0)

Page 16: Advanced Components. Components Testing. Ngrxiproduct.org/wp-content/uploads/2017/04/Angular2_TypeScript_Iliev_2016_07.pdf · Testing Configuration with Webpack webpack.test.js –

IPT – Intellectual Products & Technologies http://www.iproduct.org/

Angular 2 and TypeScript Web Application Development

Slide 16Copyright © 2003-2017 IPT – Intellectual Products & Technologies Ltd. All rights reserved.

Testing Configuration with Webpack

webpack.test.js – theWebpack testing configuration

karma-conf.js – the main config file for Karma test runner

karma-test-shim.js – initializes the TestBed (testing environment), requires all individual tests (based on provided pattern), and all necessary modules for testing, including @angular/core/testing, and @angular/platform-browser-dynamic/testing

For each componets e.g. /app/feature/my.component.ts there should be a corresppnding unit tests file named /app/feature/my.component.spec.ts

Page 17: Advanced Components. Components Testing. Ngrxiproduct.org/wp-content/uploads/2017/04/Angular2_TypeScript_Iliev_2016_07.pdf · Testing Configuration with Webpack webpack.test.js –

IPT – Intellectual Products & Technologies http://www.iproduct.org/

Angular 2 and TypeScript Web Application Development

Slide 17Copyright © 2003-2017 IPT – Intellectual Products & Technologies Ltd. All rights reserved.

Simplest Test

describe('Testing math', () => {

it('addition should work', () => {

expect(5 + 5).toEqual(10);

});

});

Page 18: Advanced Components. Components Testing. Ngrxiproduct.org/wp-content/uploads/2017/04/Angular2_TypeScript_Iliev_2016_07.pdf · Testing Configuration with Webpack webpack.test.js –

IPT – Intellectual Products & Technologies http://www.iproduct.org/

Angular 2 and TypeScript Web Application Development

Slide 18Copyright © 2003-2017 IPT – Intellectual Products & Technologies Ltd. All rights reserved.

Simple Angular 2 Application Testdescribe('App', () => { beforeEach(() => { TestBed.configureTestingModule({ imports: [FormsModule, AppRoutingModule, CommonModule, HomeModule, ProductModule, UserModule], providers: [ BackendService, {provide: APP_BASE_HREF, useValue: '/' } ], declarations: [AppComponent, AppNavComponent, RouterLinkStubDirective, RouterOutletStubComponent]}); }); it ('should work', () => { let fixture = TestBed.createComponent(AppComponent); expect(fixture.componentInstance instanceof AppComponent) .toBe(true, 'should create AppComponent'); });});

Page 19: Advanced Components. Components Testing. Ngrxiproduct.org/wp-content/uploads/2017/04/Angular2_TypeScript_Iliev_2016_07.pdf · Testing Configuration with Webpack webpack.test.js –

IPT – Intellectual Products & Technologies http://www.iproduct.org/

Angular 2 and TypeScript Web Application Development

Slide 19Copyright © 2003-2017 IPT – Intellectual Products & Technologies Ltd. All rights reserved.

Reactive Extensions for Angular: Ngrx

RxJS powered state management for Angular applications, inspired by Redux

State is a single immutable data structure

Actions describe state changes

Pure functions called reducers take the previous state and the next action to compute the new state

State accessed with the Store, an observable of state and an observer of actions

Enables building components using the OnPush change detection strategy → performant change detection

Source: @ngrx/store in GitHub, https://github.com/ngrx/store,License: MIT

Page 20: Advanced Components. Components Testing. Ngrxiproduct.org/wp-content/uploads/2017/04/Angular2_TypeScript_Iliev_2016_07.pdf · Testing Configuration with Webpack webpack.test.js –

IPT – Intellectual Products & Technologies http://www.iproduct.org/

Angular 2 and TypeScript Web Application Development

Slide 20Copyright © 2003-2017 IPT – Intellectual Products & Technologies Ltd. All rights reserved.

Installing Ngrx & Examples[https://github.com/ngrx/store]

Source: @ngrx/store in GitHub, https://github.com/ngrx/store,License: MIT

npm install @ngrx/core @ngrx/store --saveOptional packages:

@ngrx/store-devtools – instruments your store letting you use a powerful time-travelling debugger@ngrx/router-store – keeps the state of @angular/router in your store@ngrx/effects – isolates side effects from your UI by expressing side effects as sources of actions

Examples:@ngrx/example-app – best practices for @ngrx projects

angular-webpack2-starter – includes: Webpack 2, @ngrx. AOT, HMR, devtools, and server-side rendering

Page 21: Advanced Components. Components Testing. Ngrxiproduct.org/wp-content/uploads/2017/04/Angular2_TypeScript_Iliev_2016_07.pdf · Testing Configuration with Webpack webpack.test.js –

IPT – Intellectual Products & Technologies http://www.iproduct.org/

Angular 2 and TypeScript Web Application Development

Slide 21Copyright © 2003-2017 IPT – Intellectual Products & Technologies Ltd. All rights reserved.

Thanks for Your Attention!

Questions?