Skip to content

Commit

Permalink
feat: initial implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
ike18t committed Jan 23, 2018
0 parents commit 893f83b
Show file tree
Hide file tree
Showing 13 changed files with 10,042 additions and 0 deletions.
7 changes: 7 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
coverage
definitions
node_modules
**/tags*
dist
.DS_Store
.idea/
21 changes: 21 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
language: node_js
node_js:
- "v6.11.1"
- "v7.10.1"
- "v8.0.0"
sudo: required
dist: trusty
addons:
chrome: stable
before_script:
- "sudo chown root /opt/google/chrome/chrome-sandbox"
- "sudo chmod 4755 /opt/google/chrome/chrome-sandbox"
before_install:
- npm cache clean --force
matrix:
notifications:
email:
recipients:
- ike18t@gmail.com
on_success: change
on_failure: change
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2017 Isaac Datlof

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
[![Build Status](https://travis-ci.org/ike18t/mock_directive.png?branch=master)](https://travis-ci.org/ike18t/mock_directive)
[![npm version](https://badge.fury.io/js/mock-directive.svg)](https://badge.fury.io/js/mock-directive)

# mock_direcive
Helper function for creating angular directive mocks for test.

It does this by leveraging reflect-metadata to get the directive argument's selector, inputs, and outputs.

## Usage Examples: [mock_directive.spec.ts](lib/mock_directive.spec.ts)
33 changes: 33 additions & 0 deletions gulpfile.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
const gulp = require('gulp');
const ts = require('gulp-typescript');
const clean = require('gulp-clean');
const runSequence = require('run-sequence');
const merge = require('merge2');
const tslint = require('gulp-tslint');

gulp.task('build', function() {
const tsProject = ts.createProject('tsconfig.json');

var tsResult = tsProject.src()
.pipe(tsProject());

return merge([
tsResult.dts.pipe(gulp.dest('./definitions')),
tsResult.js.pipe(gulp.dest(tsProject.config.compilerOptions.outDir))
]);
});

gulp.task('clean', function () {
return gulp.src('dist', { read: false })
.pipe(clean());
});

gulp.task('lint', function() {
return gulp.src(['lib/**', 'spec/**'])
.pipe(tslint({ formatter: 'stylish' }))
.pipe(tslint.report());
});

gulp.task('default', [], function(cb) {
runSequence('clean', 'build', cb);
});
1 change: 1 addition & 0 deletions index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { MockDirective } from './lib/mock_directive';
34 changes: 34 additions & 0 deletions karma.conf.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// Karma configuration
// Generated on Mon Dec 25 2017 20:41:30 GMT-0800 (PST)

module.exports = (config: any) => {
config.set({
autoWatch: false,
browsers: ['ChromeHeadless'],
colors: true,
files: [
'node_modules/zone.js/dist/zone.js',
'node_modules/zone.js/dist/long-stack-trace-zone.js',
'node_modules/zone.js/dist/proxy.js',
'node_modules/zone.js/dist/sync-test.js',
'node_modules/zone.js/dist/jasmine-patch.js',
'node_modules/zone.js/dist/async-test.js',
'node_modules/zone.js/dist/fake-async-test.js',
{ pattern: 'lib/**/*.ts' }
],
frameworks: ['jasmine', 'karma-typescript'],
logLevel: config.LOG_INFO,
port: 9876,
preprocessors: {
'**/*.ts': ['karma-typescript']
},
reporters: ['dots', 'karma-typescript', 'kjhtml'],
singleRun: true,

karmaTypescriptConfig: {
compilerOptions: {
lib: ['ES2015', 'DOM']
}
}
});
};
61 changes: 61 additions & 0 deletions lib/mock_directive.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { Component, Directive, Input, Type } from '@angular/core';
import { async, ComponentFixture, getTestBed, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import {
BrowserDynamicTestingModule,
platformBrowserDynamicTesting
} from '@angular/platform-browser-dynamic/testing';
import { MockDirective } from './mock_directive';

@Directive({
selector: '[exampleDirective]'
})
export class ExampleDirective {
@Input() exampleDirective: string;
@Input() something: string;
}

@Component({
selector: 'example-component-container',
template: `
<div [exampleDirective]="'bye'" [something]="'hi'"></div>
`
})
export class ExampleComponentContainer {}

describe('MockComponent', () => {
let fixture: ComponentFixture<ExampleComponentContainer>;
let directive: Type<ExampleDirective>;

getTestBed().initTestEnvironment(
BrowserDynamicTestingModule,
platformBrowserDynamicTesting()
);

beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
ExampleComponentContainer,
directive = MockDirective(ExampleDirective)
]
})
.compileComponents();
}));

beforeEach(() => {
fixture = TestBed.createComponent(ExampleComponentContainer);
fixture.detectChanges();
});

it('should have use the original component\'s selector', () => {
const element = fixture.debugElement.query(By.directive(directive));
expect(element).not.toBeNull();
});

it('should have the input set on the mock component', () => {
const debugElement = fixture.debugElement.query(By.directive(directive));
const element = debugElement.injector.get(directive);
expect(element.something).toEqual('hi');
expect(element.exampleDirective).toEqual('bye');
});
});
33 changes: 33 additions & 0 deletions lib/mock_directive.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { Directive, Type } from '@angular/core';

export function MockDirective<TDirective>(directive: Type<TDirective>): Type<TDirective> {
const propertyMetadata = getPropertyMetadata(directive);

const options = {
inputs: new Array<string>(),
selector: getSelector(directive),
};

options.inputs = Object.keys(propertyMetadata).filter((meta) => isInput(propertyMetadata[meta]));

class DirectiveMock {}

/* tslint:disable:no-angle-bracket-type-assertion */
return Directive(options as Directive)(<any> DirectiveMock as Type<TDirective>);
/* tslint:enable:no-angle-bracket-type-assertion */
}

function isInput(propertyMetadata: any): boolean {
return propertyMetadata[0].ngMetadataName === 'Input';
}

function getSelector(directive: any): string {
if (directive.__annotations__) {
return directive.__annotations__[0].selector;
}
throw new Error('No annotation or decoration metadata on your directive');
}

function getPropertyMetadata(directive: any): any {
return directive.__prop__metadata__ || {};
}
Loading

0 comments on commit 893f83b

Please sign in to comment.