├── src ├── assets │ └── .gitkeep ├── favicon.ico ├── styles.css ├── environments │ ├── environment.prod.ts │ └── environment.ts ├── typings.d.ts ├── testing │ ├── matcher-types.d.ts │ ├── matchers.ts │ ├── test-context.ts │ ├── init.ts │ └── spec-builder.ts ├── app │ ├── greet │ │ ├── greet.component.ts │ │ └── greet.component.spec.ts │ ├── app.component.ts │ ├── name-form │ │ ├── name-form.component.ts │ │ └── name-form.component.spec.ts │ └── app.module.ts ├── tsconfig.app.json ├── index.html ├── main.ts ├── tsconfig.spec.json ├── test.ts └── polyfills.ts ├── e2e ├── app.po.ts ├── tsconfig.e2e.json └── app.e2e-spec.ts ├── .editorconfig ├── tsconfig.json ├── .gitignore ├── protractor.conf.js ├── karma.conf.js ├── LICENSE ├── README.md ├── package.json ├── tslint.json └── angular.json /src/assets/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/youdz/dry-angular-testing/HEAD/src/favicon.ico -------------------------------------------------------------------------------- /src/styles.css: -------------------------------------------------------------------------------- 1 | /* You can add global styles to this file, and also import other style files */ 2 | -------------------------------------------------------------------------------- /src/environments/environment.prod.ts: -------------------------------------------------------------------------------- 1 | export const environment = { 2 | production: true 3 | }; 4 | -------------------------------------------------------------------------------- /src/typings.d.ts: -------------------------------------------------------------------------------- 1 | /* SystemJS module definition */ 2 | declare var module: NodeModule; 3 | interface NodeModule { 4 | id: string; 5 | } 6 | -------------------------------------------------------------------------------- /src/testing/matcher-types.d.ts: -------------------------------------------------------------------------------- 1 | declare namespace jasmine { 2 | interface Matchers { 3 | toDisplay(expected: string): boolean; 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /src/app/greet/greet.component.ts: -------------------------------------------------------------------------------- 1 | import {Component, Input} from '@angular/core'; 2 | 3 | @Component({ 4 | selector: 'app-greet', 5 | template: ` 6 |

Hello {{name}}

7 | ` 8 | }) 9 | export class GreetComponent { 10 | @Input() name: string; 11 | } 12 | -------------------------------------------------------------------------------- /e2e/app.po.ts: -------------------------------------------------------------------------------- 1 | import { browser, by, element } from 'protractor'; 2 | 3 | export class DryTestingPage { 4 | navigateTo() { 5 | return browser.get('/'); 6 | } 7 | 8 | getParagraphText() { 9 | return element(by.css('app-root h1')).getText(); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/tsconfig.app.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/app", 5 | "baseUrl": "./", 6 | "module": "es2015", 7 | "types": [] 8 | }, 9 | "exclude": [ 10 | "test.ts", 11 | "testing/", 12 | "**/*.spec.ts" 13 | ] 14 | } 15 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # Editor configuration, see http://editorconfig.org 2 | root = true 3 | 4 | [*] 5 | charset = utf-8 6 | indent_style = space 7 | indent_size = 2 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | 11 | [*.md] 12 | max_line_length = off 13 | trim_trailing_whitespace = false 14 | -------------------------------------------------------------------------------- /e2e/tsconfig.e2e.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/e2e", 5 | "baseUrl": "./", 6 | "module": "commonjs", 7 | "target": "es5", 8 | "types": [ 9 | "jasmine", 10 | "jasminewd2", 11 | "node" 12 | ] 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/app/app.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | 3 | @Component({ 4 | selector: 'app-root', 5 | template: ` 6 | 7 | 8 | ` 9 | }) 10 | export class AppComponent { 11 | username = 'World'; 12 | } 13 | -------------------------------------------------------------------------------- /src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | DryTesting 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import { enableProdMode } from '@angular/core'; 2 | import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; 3 | 4 | import { AppModule } from './app/app.module'; 5 | import { environment } from './environments/environment'; 6 | 7 | if (environment.production) { 8 | enableProdMode(); 9 | } 10 | 11 | platformBrowserDynamic().bootstrapModule(AppModule); 12 | -------------------------------------------------------------------------------- /e2e/app.e2e-spec.ts: -------------------------------------------------------------------------------- 1 | import { DryTestingPage } from './app.po'; 2 | 3 | describe('dry-testing App', () => { 4 | let page: DryTestingPage; 5 | 6 | beforeEach(() => { 7 | page = new DryTestingPage(); 8 | }); 9 | 10 | it('should display welcome message', () => { 11 | page.navigateTo(); 12 | expect(page.getParagraphText()).toEqual('Welcome to app!'); 13 | }); 14 | }); 15 | -------------------------------------------------------------------------------- /src/environments/environment.ts: -------------------------------------------------------------------------------- 1 | // The file contents for the current environment will overwrite these during build. 2 | // The build system defaults to the dev environment which uses `environment.ts`, but if you do 3 | // `ng build --env=prod` then `environment.prod.ts` will be used instead. 4 | // The list of which env maps to which file can be found in `.angular-cli.json`. 5 | 6 | export const environment = { 7 | production: false 8 | }; 9 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compileOnSave": false, 3 | "compilerOptions": { 4 | "outDir": "./dist/out-tsc", 5 | "sourceMap": true, 6 | "declaration": false, 7 | "moduleResolution": "node", 8 | "emitDecoratorMetadata": true, 9 | "experimentalDecorators": true, 10 | "target": "es5", 11 | "typeRoots": [ 12 | "node_modules/@types" 13 | ], 14 | "lib": [ 15 | "es2016", 16 | "dom" 17 | ] 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/tsconfig.spec.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/spec", 5 | "baseUrl": "./", 6 | "module": "commonjs", 7 | "target": "es5", 8 | "types": [ 9 | "jasmine", 10 | "node" 11 | ] 12 | }, 13 | "files": [ 14 | "test.ts", 15 | "polyfills.ts" 16 | ], 17 | "include": [ 18 | "testing/*.ts", 19 | "**/*.spec.ts", 20 | "**/*.d.ts" 21 | ] 22 | } 23 | -------------------------------------------------------------------------------- /src/app/name-form/name-form.component.ts: -------------------------------------------------------------------------------- 1 | import {Component, EventEmitter, Input, Output} from '@angular/core'; 2 | 3 | @Component({ 4 | selector: 'app-name-form', 5 | template: ` 6 | 7 | 8 | ` 9 | }) 10 | export class NameFormComponent { 11 | @Input() name: string; 12 | @Output() nameChange = new EventEmitter(); 13 | 14 | update(newValue: string) { 15 | this.name = newValue; 16 | this.nameChange.emit(newValue); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/app/app.module.ts: -------------------------------------------------------------------------------- 1 | import { BrowserModule } from '@angular/platform-browser'; 2 | import { NgModule } from '@angular/core'; 3 | 4 | import { AppComponent } from './app.component'; 5 | import { GreetComponent } from './greet/greet.component'; 6 | import { NameFormComponent } from './name-form/name-form.component'; 7 | 8 | @NgModule({ 9 | declarations: [ 10 | AppComponent, 11 | GreetComponent, 12 | NameFormComponent 13 | ], 14 | imports: [ 15 | BrowserModule 16 | ], 17 | providers: [], 18 | bootstrap: [AppComponent] 19 | }) 20 | export class AppModule { } 21 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See http://help.github.com/ignore-files/ for more about ignoring files. 2 | 3 | # compiled output 4 | /dist 5 | /tmp 6 | /out-tsc 7 | 8 | # dependencies 9 | /node_modules 10 | 11 | # IDEs and editors 12 | /.idea 13 | .project 14 | .classpath 15 | .c9/ 16 | *.launch 17 | .settings/ 18 | *.sublime-workspace 19 | 20 | # IDE - VSCode 21 | .vscode/* 22 | !.vscode/settings.json 23 | !.vscode/tasks.json 24 | !.vscode/launch.json 25 | !.vscode/extensions.json 26 | 27 | # misc 28 | /.sass-cache 29 | /connect.lock 30 | /coverage 31 | /libpeerconnection.log 32 | npm-debug.log 33 | testem.log 34 | /typings 35 | 36 | # e2e 37 | /e2e/*.js 38 | /e2e/*.map 39 | 40 | # System Files 41 | .DS_Store 42 | Thumbs.db 43 | -------------------------------------------------------------------------------- /protractor.conf.js: -------------------------------------------------------------------------------- 1 | // Protractor configuration file, see link for more information 2 | // https://github.com/angular/protractor/blob/master/lib/config.ts 3 | 4 | const { SpecReporter } = require('jasmine-spec-reporter'); 5 | 6 | exports.config = { 7 | allScriptsTimeout: 11000, 8 | specs: [ 9 | './e2e/**/*.e2e-spec.ts' 10 | ], 11 | capabilities: { 12 | 'browserName': 'chrome' 13 | }, 14 | directConnect: true, 15 | baseUrl: 'http://localhost:4200/', 16 | framework: 'jasmine', 17 | jasmineNodeOpts: { 18 | showColors: true, 19 | defaultTimeoutInterval: 30000, 20 | print: function() {} 21 | }, 22 | onPrepare() { 23 | require('ts-node').register({ 24 | project: 'e2e/tsconfig.e2e.json' 25 | }); 26 | jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } })); 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /src/testing/matchers.ts: -------------------------------------------------------------------------------- 1 | import {TestContext} from './test-context'; 2 | 3 | export const MATCHERS: jasmine.CustomMatcherFactories = { 4 | toDisplay: function(util, customEqualityTesters) { 5 | return { 6 | compare: function(actual: TestContext, expected: string) { 7 | const textContent = actual.fixture.debugElement.nativeElement.textContent; 8 | const pass = util.contains(textContent, expected, customEqualityTesters); 9 | let message: string; 10 | if (pass) { 11 | message = `Expected ${actual.fixture.debugElement.nativeElement.innerHTML} not to display ${expected}`; 12 | } else { 13 | message = `Expected ${actual.fixture.debugElement.nativeElement.innerHTML} to display ${expected}`; 14 | } 15 | return {pass, message}; 16 | } 17 | }; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /src/testing/test-context.ts: -------------------------------------------------------------------------------- 1 | import {DebugElement} from '@angular/core'; 2 | import {ComponentFixture} from '@angular/core/testing'; 3 | import {By} from '@angular/platform-browser'; 4 | 5 | export class TestContext { 6 | fixture: ComponentFixture; 7 | hostComponent: H; 8 | tested: DebugElement; 9 | testedDirective: T; 10 | testedElement: any; 11 | 12 | /* 13 | * Add any shortcuts you may need. 14 | * Here is an example of one, but you could for instance add shortcuts to: 15 | * - query native elements directly by CSS selector 16 | * - request providers from the tested directive's injector 17 | * - ... 18 | */ 19 | detectChanges() { 20 | this.fixture.detectChanges(); 21 | } 22 | 23 | query(cssSelector: string) { 24 | return this.fixture.debugElement.query(By.css(cssSelector)); 25 | } 26 | } 27 | 28 | 29 | -------------------------------------------------------------------------------- /karma.conf.js: -------------------------------------------------------------------------------- 1 | // Karma configuration file, see link for more information 2 | // https://karma-runner.github.io/0.13/config/configuration-file.html 3 | 4 | module.exports = function (config) { 5 | config.set({ 6 | basePath: '', 7 | frameworks: ['jasmine', '@angular-devkit/build-angular'], 8 | plugins: [ 9 | require('karma-jasmine'), 10 | require('karma-chrome-launcher'), 11 | require('karma-jasmine-html-reporter'), 12 | require('karma-coverage-istanbul-reporter'), 13 | require('@angular-devkit/build-angular/plugins/karma') 14 | ], 15 | client:{ 16 | clearContext: false // leave Jasmine Spec Runner output visible in browser 17 | }, 18 | coverageIstanbulReporter: { 19 | dir: require('path').join(__dirname, 'coverage'), reports: [ 'html', 'lcovonly' ], 20 | fixWebpackSourcePaths: true 21 | }, 22 | angularCli: { 23 | environment: 'dev' 24 | }, 25 | reporters: ['progress', 'kjhtml'], 26 | port: 9876, 27 | colors: true, 28 | logLevel: config.LOG_INFO, 29 | autoWatch: true, 30 | browsers: ['Chrome'], 31 | singleRun: false 32 | }); 33 | }; 34 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Eudes Petonnet-Vincent 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/test.ts: -------------------------------------------------------------------------------- 1 | // This file is required by karma.conf.js and loads recursively all the .spec and framework files 2 | 3 | import 'zone.js/dist/long-stack-trace-zone'; 4 | import 'zone.js/dist/proxy.js'; 5 | import 'zone.js/dist/sync-test'; 6 | import 'zone.js/dist/jasmine-patch'; 7 | import 'zone.js/dist/async-test'; 8 | import 'zone.js/dist/fake-async-test'; 9 | import { getTestBed } from '@angular/core/testing'; 10 | import { 11 | BrowserDynamicTestingModule, 12 | platformBrowserDynamicTesting 13 | } from '@angular/platform-browser-dynamic/testing'; 14 | 15 | // Unfortunately there's no typing for the `__karma__` variable. Just declare it as any. 16 | declare const __karma__: any; 17 | declare const require: any; 18 | 19 | // Prevent Karma from running prematurely. 20 | __karma__.loaded = function () {}; 21 | 22 | // First, initialize the Angular testing environment. 23 | getTestBed().initTestEnvironment( 24 | BrowserDynamicTestingModule, 25 | platformBrowserDynamicTesting() 26 | ); 27 | // Then we find all the tests. 28 | const context = require.context('./', true, /\.spec\.ts$/); 29 | // And load the modules. 30 | context.keys().map(context); 31 | // Finally, start Karma to run the tests. 32 | __karma__.start(); 33 | -------------------------------------------------------------------------------- /src/app/greet/greet.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | 3 | import {initContext} from '../../testing/init'; 4 | import {TestContext} from '../../testing/test-context'; 5 | import {ComponentSpec} from '../../testing/spec-builder'; 6 | import { GreetComponent } from './greet.component'; 7 | 8 | @Component({ 9 | template: ` 10 | 11 | ` 12 | }) 13 | class TestComponent { 14 | name = 'World'; 15 | } 16 | 17 | describe('GreetComponent', () => { 18 | type Context = TestContext; 19 | initContext(GreetComponent, TestComponent); 20 | 21 | it('receives a [name] input', function(this: Context) { 22 | this.hostComponent.name = 'Angular'; 23 | this.detectChanges(); 24 | expect(this.testedDirective.name).toBe('Angular'); 25 | }); 26 | 27 | it('greets politely', function(this: Context) { 28 | expect(this).toDisplay('Hello World'); 29 | }); 30 | }); 31 | 32 | 33 | 34 | /* 35 | * Experimenting with a spec builder for even simpler unit testing 36 | */ 37 | 38 | const spec = new ComponentSpec(GreetComponent); 39 | spec.hasInput('name'); 40 | spec.set('name', 'World').displays('Hello World'); 41 | spec.run(); 42 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # DRY Angular testing 2 | 3 | This project showcases the use of a test context, passed through Jasmine's user context, 4 | to avoid code duplication and centralizes the use of Angular's testing utilities. 5 | For more information on how this works, check out 6 | [this blog post](https://medium.com/claritydesignsystem/angular-testing-made-easy-4e11f6044129) 7 | (the actual code has slightly evolved since then, but the explanation is still valid). 8 | 9 | ## Angular CLI use 10 | 11 | This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 1.2.1. 12 | 13 | ### Development server 14 | 15 | Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files. 16 | 17 | ### Code scaffolding 18 | 19 | Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|module`. 20 | 21 | ### Running unit tests 22 | 23 | Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io). 24 | 25 | ### Further help 26 | 27 | To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/master/README.md). 28 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "dry-testing", 3 | "version": "0.0.0", 4 | "license": "MIT", 5 | "scripts": { 6 | "ng": "ng", 7 | "start": "ng serve", 8 | "build": "ng build", 9 | "test": "ng test", 10 | "lint": "ng lint", 11 | "e2e": "ng e2e" 12 | }, 13 | "private": true, 14 | "dependencies": { 15 | "@angular/animations": "^7.2.2", 16 | "@angular/common": "^7.2.2", 17 | "@angular/compiler": "^7.2.2", 18 | "@angular/core": "^7.2.2", 19 | "@angular/forms": "^7.2.2", 20 | "@angular/http": "^7.2.2", 21 | "@angular/platform-browser": "^7.2.2", 22 | "@angular/platform-browser-dynamic": "^7.2.2", 23 | "@angular/router": "^7.2.2", 24 | "core-js": "^2.6.3", 25 | "rxjs": "^6.3.3", 26 | "zone.js": "0.8.29", 27 | "rxjs-compat": "^6.0.0-rc.0" 28 | }, 29 | "devDependencies": { 30 | "@angular-devkit/build-angular": "^0.12.3", 31 | "@angular/cli": "^7.2.3", 32 | "@angular/compiler-cli": "^7.2.2", 33 | "@angular/language-service": "^7.2.2", 34 | "@types/jasmine": "^3.3.7", 35 | "@types/jasminewd2": "^2.0.6", 36 | "@types/node": "^10.12.18", 37 | "codelyzer": "~4.5.0", 38 | "jasmine-core": "~3.3.0", 39 | "jasmine-spec-reporter": "~4.2.1", 40 | "karma": "~4.0.0", 41 | "karma-chrome-launcher": "~2.2.0", 42 | "karma-cli": "~2.0.0", 43 | "karma-coverage-istanbul-reporter": "^2.0.4", 44 | "karma-jasmine": "~2.0.1", 45 | "karma-jasmine-html-reporter": "^1.4.0", 46 | "protractor": "~5.4.2", 47 | "ts-node": "~8.0.1", 48 | "tslint": "~5.12.1", 49 | "typescript": "~3.2.4" 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/app/name-form/name-form.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | 3 | import {initContext} from '../../testing/init'; 4 | import {TestContext} from '../../testing/test-context'; 5 | import {ComponentSpec} from '../../testing/spec-builder'; 6 | import { NameFormComponent } from './name-form.component'; 7 | 8 | @Component({ 9 | template: ` 10 | 11 | ` 12 | }) 13 | class TestComponent { 14 | name: string; 15 | } 16 | 17 | describe('NameFormComponent', () => { 18 | type Context = TestContext; 19 | initContext(NameFormComponent, TestComponent); 20 | 21 | it('offers a [(name)] two-way binding', function(this: Context) { 22 | // Input 23 | this.hostComponent.name = 'World'; 24 | this.detectChanges(); 25 | expect(this.testedDirective.name).toBe('World'); 26 | // Output 27 | this.testedDirective.update('Angular'); 28 | this.detectChanges(); 29 | expect(this.hostComponent.name).toBe('Angular'); 30 | }); 31 | 32 | it('updates and emits the (nameChange) output on input change', function(this: Context) { 33 | const input = this.query('input'); 34 | input.nativeElement.value = 'World'; 35 | input.triggerEventHandler('change', null); 36 | this.detectChanges(); 37 | expect(this.testedDirective.name).toBe('World'); 38 | expect(this.hostComponent.name).toBe('World'); 39 | }); 40 | }); 41 | 42 | 43 | /* 44 | * Experimenting with a spec builder for even simpler unit testing 45 | */ 46 | 47 | const spec = new ComponentSpec(NameFormComponent); 48 | // spec.hasInput('name'); 49 | // spec.hasOutput('nameChange'); 50 | spec.hasTwoWayBinding('name'); 51 | spec.run(); 52 | -------------------------------------------------------------------------------- /src/testing/init.ts: -------------------------------------------------------------------------------- 1 | import {MATCHERS} from './matchers'; 2 | import {Type} from '@angular/core'; 3 | import {async, TestBed, TestModuleMetadata} from '@angular/core/testing'; 4 | import {By} from '@angular/platform-browser'; 5 | import {TestContext} from './test-context'; 6 | 7 | export function initContext(testedType: Type, hostType: Type, moduleMetadata: TestModuleMetadata = {}) { 8 | beforeEach(function() { 9 | /* 10 | * I feel dirty writing this, but Jasmine creates plain objects 11 | * and modifying their prototype is definitely a bad idea 12 | */ 13 | Object.assign(this, TestContext.prototype); 14 | // We add the custom matchers that work directly on TestContext 15 | jasmine.addMatchers(MATCHERS); 16 | }); 17 | 18 | beforeEach(async(function(this: TestContext) { 19 | const declarations = [ testedType, hostType ]; 20 | if (moduleMetadata && moduleMetadata.declarations) { 21 | declarations.push(...moduleMetadata.declarations); 22 | } 23 | TestBed.configureTestingModule({...moduleMetadata, declarations: declarations}) 24 | .compileComponents(); 25 | })); 26 | 27 | beforeEach(function(this: TestContext) { 28 | this.fixture = TestBed.createComponent(hostType); 29 | this.fixture.detectChanges(); 30 | this.hostComponent = this.fixture.componentInstance; 31 | const testedDebugElement = this.fixture.debugElement.query(By.directive(testedType)); 32 | // On larger project, it would be recommended to throw an error here if the tested directive can't be found. 33 | this.tested = testedDebugElement; 34 | this.testedDirective = testedDebugElement.injector.get(testedType); 35 | this.testedElement = testedDebugElement.nativeElement; 36 | }); 37 | 38 | afterEach(function(this: TestContext) { 39 | if (this.fixture) { 40 | this.fixture.destroy(); 41 | this.fixture.nativeElement.remove(); 42 | } 43 | }); 44 | } 45 | -------------------------------------------------------------------------------- /src/polyfills.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file includes polyfills needed by Angular and is loaded before the app. 3 | * You can add your own extra polyfills to this file. 4 | * 5 | * This file is divided into 2 sections: 6 | * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers. 7 | * 2. Application imports. Files imported after ZoneJS that should be loaded before your main 8 | * file. 9 | * 10 | * The current setup is for so-called "evergreen" browsers; the last versions of browsers that 11 | * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera), 12 | * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile. 13 | * 14 | * Learn more in https://angular.io/docs/ts/latest/guide/browser-support.html 15 | */ 16 | 17 | /*************************************************************************************************** 18 | * BROWSER POLYFILLS 19 | */ 20 | 21 | /** IE9, IE10 and IE11 requires all of the following polyfills. **/ 22 | // import 'core-js/es6/symbol'; 23 | // import 'core-js/es6/object'; 24 | // import 'core-js/es6/function'; 25 | // import 'core-js/es6/parse-int'; 26 | // import 'core-js/es6/parse-float'; 27 | // import 'core-js/es6/number'; 28 | // import 'core-js/es6/math'; 29 | // import 'core-js/es6/string'; 30 | // import 'core-js/es6/date'; 31 | // import 'core-js/es6/array'; 32 | // import 'core-js/es6/regexp'; 33 | // import 'core-js/es6/map'; 34 | // import 'core-js/es6/weak-map'; 35 | // import 'core-js/es6/set'; 36 | 37 | /** IE10 and IE11 requires the following for NgClass support on SVG elements */ 38 | // import 'classlist.js'; // Run `npm install --save classlist.js`. 39 | 40 | /** Evergreen browsers require these. **/ 41 | import 'core-js/es6/reflect'; 42 | import 'core-js/es7/reflect'; 43 | 44 | 45 | /** 46 | * Required to support Web Animations `@angular/animation`. 47 | * Needed for: All but Chrome, Firefox and Opera. http://caniuse.com/#feat=web-animation 48 | **/ 49 | // import 'web-animations-js'; // Run `npm install --save web-animations-js`. 50 | 51 | 52 | 53 | /*************************************************************************************************** 54 | * Zone JS is required by Angular itself. 55 | */ 56 | import 'zone.js/dist/zone'; // Included with Angular CLI. 57 | 58 | 59 | 60 | /*************************************************************************************************** 61 | * APPLICATION IMPORTS 62 | */ 63 | 64 | /** 65 | * Date, currency, decimal and percent pipes. 66 | * Needed for: All but Chrome, Firefox, Edge, IE11 and Safari 10 67 | */ 68 | // import 'intl'; // Run `npm install --save intl`. 69 | /** 70 | * Need to import at least one locale-data with intl. 71 | */ 72 | // import 'intl/locale-data/jsonp/en'; 73 | -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "rulesDirectory": [ 3 | "node_modules/codelyzer" 4 | ], 5 | "rules": { 6 | "arrow-return-shorthand": true, 7 | "callable-types": true, 8 | "class-name": true, 9 | "comment-format": [ 10 | true, 11 | "check-space" 12 | ], 13 | "curly": true, 14 | "eofline": true, 15 | "forin": true, 16 | "import-blacklist": [ 17 | true 18 | ], 19 | "import-spacing": true, 20 | "indent": [ 21 | true, 22 | "spaces" 23 | ], 24 | "interface-over-type-literal": true, 25 | "label-position": true, 26 | "max-line-length": [ 27 | true, 28 | 140 29 | ], 30 | "member-access": false, 31 | "member-ordering": [ 32 | true, 33 | { 34 | "order": [ 35 | "static-field", 36 | "instance-field", 37 | "static-method", 38 | "instance-method" 39 | ] 40 | } 41 | ], 42 | "no-arg": true, 43 | "no-bitwise": true, 44 | "no-console": [ 45 | true, 46 | "debug", 47 | "info", 48 | "time", 49 | "timeEnd", 50 | "trace" 51 | ], 52 | "no-construct": true, 53 | "no-debugger": true, 54 | "no-duplicate-super": true, 55 | "no-empty": false, 56 | "no-empty-interface": true, 57 | "no-eval": true, 58 | "no-inferrable-types": [ 59 | true, 60 | "ignore-params" 61 | ], 62 | "no-misused-new": true, 63 | "no-non-null-assertion": true, 64 | "no-shadowed-variable": true, 65 | "no-string-literal": false, 66 | "no-string-throw": true, 67 | "no-switch-case-fall-through": true, 68 | "no-trailing-whitespace": true, 69 | "no-unnecessary-initializer": true, 70 | "no-unused-expression": true, 71 | "no-use-before-declare": true, 72 | "no-var-keyword": true, 73 | "object-literal-sort-keys": false, 74 | "one-line": [ 75 | true, 76 | "check-open-brace", 77 | "check-catch", 78 | "check-else", 79 | "check-whitespace" 80 | ], 81 | "prefer-const": true, 82 | "quotemark": [ 83 | true, 84 | "single" 85 | ], 86 | "radix": true, 87 | "semicolon": [ 88 | true, 89 | "always" 90 | ], 91 | "triple-equals": [ 92 | true, 93 | "allow-null-check" 94 | ], 95 | "typedef-whitespace": [ 96 | true, 97 | { 98 | "call-signature": "nospace", 99 | "index-signature": "nospace", 100 | "parameter": "nospace", 101 | "property-declaration": "nospace", 102 | "variable-declaration": "nospace" 103 | } 104 | ], 105 | "typeof-compare": true, 106 | "unified-signatures": true, 107 | "variable-name": false, 108 | "whitespace": [ 109 | true, 110 | "check-branch", 111 | "check-decl", 112 | "check-operator", 113 | "check-separator", 114 | "check-type" 115 | ], 116 | "directive-selector": [ 117 | true, 118 | "attribute", 119 | "app", 120 | "camelCase" 121 | ], 122 | "component-selector": [ 123 | true, 124 | "element", 125 | "app", 126 | "kebab-case" 127 | ], 128 | "use-input-property-decorator": true, 129 | "use-output-property-decorator": true, 130 | "use-host-property-decorator": true, 131 | "no-input-rename": true, 132 | "no-output-rename": true, 133 | "use-life-cycle-interface": true, 134 | "use-pipe-transform-interface": true, 135 | "component-class-suffix": true, 136 | "directive-class-suffix": true, 137 | "no-access-missing-member": true, 138 | "templates-use-public": true, 139 | "invoke-injectable": true 140 | } 141 | } 142 | -------------------------------------------------------------------------------- /angular.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "./node_modules/@angular/cli/lib/config/schema.json", 3 | "version": 1, 4 | "newProjectRoot": "projects", 5 | "projects": { 6 | "dry-testing": { 7 | "root": "", 8 | "sourceRoot": "src", 9 | "projectType": "application", 10 | "architect": { 11 | "build": { 12 | "builder": "@angular-devkit/build-angular:browser", 13 | "options": { 14 | "outputPath": "dist", 15 | "index": "src/index.html", 16 | "main": "src/main.ts", 17 | "tsConfig": "src/tsconfig.app.json", 18 | "polyfills": "src/polyfills.ts", 19 | "assets": [ 20 | "src/assets", 21 | "src/favicon.ico" 22 | ], 23 | "styles": [ 24 | "src/styles.css" 25 | ], 26 | "scripts": [] 27 | }, 28 | "configurations": { 29 | "production": { 30 | "optimization": true, 31 | "outputHashing": "all", 32 | "sourceMap": false, 33 | "extractCss": true, 34 | "namedChunks": false, 35 | "aot": true, 36 | "extractLicenses": true, 37 | "vendorChunk": false, 38 | "buildOptimizer": true, 39 | "fileReplacements": [ 40 | { 41 | "replace": "src/environments/environment.ts", 42 | "with": "src/environments/environment.prod.ts" 43 | } 44 | ] 45 | } 46 | } 47 | }, 48 | "serve": { 49 | "builder": "@angular-devkit/build-angular:dev-server", 50 | "options": { 51 | "browserTarget": "dry-testing:build" 52 | }, 53 | "configurations": { 54 | "production": { 55 | "browserTarget": "dry-testing:build:production" 56 | } 57 | } 58 | }, 59 | "extract-i18n": { 60 | "builder": "@angular-devkit/build-angular:extract-i18n", 61 | "options": { 62 | "browserTarget": "dry-testing:build" 63 | } 64 | }, 65 | "test": { 66 | "builder": "@angular-devkit/build-angular:karma", 67 | "options": { 68 | "main": "src/test.ts", 69 | "karmaConfig": "./karma.conf.js", 70 | "polyfills": "src/polyfills.ts", 71 | "tsConfig": "src/tsconfig.spec.json", 72 | "scripts": [], 73 | "styles": [ 74 | "src/styles.css" 75 | ], 76 | "assets": [ 77 | "src/assets", 78 | "src/favicon.ico" 79 | ] 80 | } 81 | }, 82 | "lint": { 83 | "builder": "@angular-devkit/build-angular:tslint", 84 | "options": { 85 | "tsConfig": [ 86 | "src/tsconfig.app.json", 87 | "src/tsconfig.spec.json" 88 | ], 89 | "exclude": [] 90 | } 91 | } 92 | } 93 | }, 94 | "dry-testing-e2e": { 95 | "root": "", 96 | "sourceRoot": "", 97 | "projectType": "application", 98 | "architect": { 99 | "e2e": { 100 | "builder": "@angular-devkit/build-angular:protractor", 101 | "options": { 102 | "protractorConfig": "./protractor.conf.js", 103 | "devServerTarget": "dry-testing:serve" 104 | } 105 | }, 106 | "lint": { 107 | "builder": "@angular-devkit/build-angular:tslint", 108 | "options": { 109 | "tsConfig": [ 110 | "e2e/tsconfig.e2e.json" 111 | ], 112 | "exclude": [] 113 | } 114 | } 115 | } 116 | } 117 | }, 118 | "defaultProject": "dry-testing", 119 | "schematics": { 120 | "@schematics/angular:component": { 121 | "prefix": "app", 122 | "styleext": "css" 123 | }, 124 | "@schematics/angular:directive": { 125 | "prefix": "app" 126 | } 127 | } 128 | } -------------------------------------------------------------------------------- /src/testing/spec-builder.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Highly experimental, I am just trying out ideas here. Please don't use this in production. 3 | */ 4 | 5 | import {Component, Type} from '@angular/core'; 6 | import {TestContext} from './test-context'; 7 | import {GreetComponent} from '../app/greet/greet.component'; 8 | import {TestBed, TestModuleMetadata} from '@angular/core/testing'; 9 | import {By} from '@angular/platform-browser'; 10 | import {MATCHERS} from './matchers'; 11 | 12 | const ANNOTATIONS = '__annotations__'; 13 | 14 | @Component({ 15 | template: `` 16 | }) 17 | export class TestComponent { 18 | 19 | } 20 | 21 | export class ComponentSpec { 22 | constructor(public componentClass: Type) {} 23 | 24 | private specs: (() => void)[] = []; 25 | private setups: (() => void)[] = []; 26 | private moduleMetadata: TestModuleMetadata = {declarations: [ this.componentClass, TestComponent ]}; 27 | 28 | private get selector() { 29 | // FIXME: obviously this uses private Angular APIs and only works in my simple examples. Just prototyping. 30 | return this.componentClass[ANNOTATIONS][0].selector; 31 | } 32 | 33 | configureTestingModule(moduleDef: TestModuleMetadata) { 34 | const declarations = [ this.componentClass, TestComponent ]; 35 | if (moduleDef && moduleDef.declarations) { 36 | declarations.push(...moduleDef.declarations); 37 | } 38 | this.moduleMetadata = {...moduleDef, declarations}; 39 | return this; 40 | } 41 | 42 | private initTest(testContext: TestContext>) { 43 | TestBed.configureTestingModule(this.moduleMetadata) 44 | .overrideTemplate(TestComponent, `<${this.selector}>`) 45 | .compileComponents(); 46 | testContext.fixture = TestBed.createComponent>(TestComponent); 47 | testContext.fixture.detectChanges(); 48 | testContext.hostComponent = testContext.fixture.componentInstance; 49 | // On larger project, it would be recommended to throw an error here if the tested directive can't be found. 50 | testContext.tested = testContext.fixture.debugElement.query(By.directive(this.componentClass)); 51 | testContext.testedDirective = testContext.tested.injector.get(this.componentClass); 52 | testContext.testedElement = testContext.tested.nativeElement; 53 | } 54 | 55 | hasInput(inputProperty: keyof T, inputName?: string) { 56 | this.specs.push(() => { 57 | it('receives a [' + inputName + '] input', () => { 58 | // FIXME: obviously this isn't safe, but we're doing quick prototyping 59 | const inputs = (this.componentClass as any).ngBaseDef.inputs; 60 | expect(inputs.hasOwnProperty(inputProperty)) 61 | .toBeTruthy(`${this.componentClass.name} does not declare a @Input(${inputName || ''}) ${inputProperty}.`); 62 | expect(inputs[inputProperty]) 63 | .toBe(inputName, `${this.componentClass.name} does not declare a @Input(${inputName || ''}) ${inputProperty}.`); 64 | }); 65 | }); 66 | } 67 | 68 | hasOutput(outputProperty: keyof T, ouputName?: string) { 69 | this.specs.push(() => { 70 | it('offers a (' + ouputName + ') output', () => { 71 | // FIXME: obviously this isn't safe, but we're doing quick prototyping 72 | const inputs = (this.componentClass as any).ngBaseDef.outputs; 73 | expect(inputs.hasOwnProperty(outputProperty)) 74 | .toBeTruthy(`${this.componentClass.name} does not declare a @Output(${ouputName || ''}) ${outputProperty}.`); 75 | expect(inputs[outputProperty]) 76 | .toBe(ouputName, `${this.componentClass.name} does not declare a @Output(${ouputName || ''}) ${outputProperty}.`); 77 | }); 78 | }); 79 | } 80 | 81 | hasTwoWayBinding(bindingProperty: keyof T, bindingName?: string) { 82 | this.hasInput(bindingProperty, bindingName); 83 | this.hasOutput((bindingProperty + 'Change'), bindingName ? bindingName + 'Change' : undefined); 84 | } 85 | 86 | setup(actions: (this: TestContext>) => void) { 87 | this.setups.push(actions); 88 | return this; 89 | } 90 | 91 | set(property: K, value: T[K]) { 92 | return this.setup(function() { this.testedDirective[property] = value; }); 93 | } 94 | 95 | displays(text: string) { 96 | const that = this; 97 | this.specs.push(() => { 98 | it('displays ' + text, function(this: TestContext>) { 99 | that.initTest(this); 100 | that.setups.forEach(s => s.call(this)); 101 | // Clear setups so the next test can have its own. 102 | that.setups.length = 0; 103 | this.fixture.detectChanges(); 104 | expect(this).toDisplay(text); 105 | this.fixture.destroy(); 106 | }); 107 | }); 108 | } 109 | 110 | run() { 111 | describe(this.componentClass.name + ' component', () => { 112 | beforeEach(() => jasmine.addMatchers(MATCHERS)); 113 | this.specs.forEach(spec => spec()); 114 | }); 115 | } 116 | 117 | } 118 | --------------------------------------------------------------------------------