Skip to content

Commit

Permalink
Implement inject fn
Browse files Browse the repository at this point in the history
  • Loading branch information
aciccarello committed Dec 26, 2016
1 parent 650c029 commit c4b11ba
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
15 changes: 15 additions & 0 deletions src/testing/inject.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { getInjectableName } from '../core/di';

/**
* Allows injecting dependencies based on their token
* @param tokens Array of injectable classes or string service names as registered with angular
* @param fn Callback fn to run with parameters matching the tokens Array
* @return angular.mock.inject called with the callback fn
*/
export function inject(tokens: any[], fn: Function): () => any {
let injectableNames = tokens.map((token) => getInjectableName(token));

fn.$inject = injectableNames;

return angular.mock.inject(fn);
}
36 changes: 36 additions & 0 deletions test/testing/inject.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { expect } from 'chai';
import * as sinon from 'sinon';
import { inject } from '../../src/testing/inject';
import { Injectable } from '../../src/core/di/decorators';
import { noop, global } from '../../src/facade/lang';

describe(`testing/inject`, () => {
describe(`inject`, () => {
function mockAngularMockInject(mockInjectFn: any) {
global.angular = { mock: {} } as any;
global.angular.mock.inject = mockInjectFn as any;
}

it('should invoke angular mock inject', () => {
const injectedVal = { text: 'This is injected' }
mockAngularMockInject((fn: Function) => fn(injectedVal));

const injectFn = sinon.spy();
inject(['$window'], injectFn)

expect( injectFn.calledWith( injectedVal ) ).to.equal( true )
});

it('should list the injectable tokens on the function', () => {
const mockInjectFn = sinon.spy();
mockAngularMockInject(mockInjectFn);

@Injectable('MyInjectable')
class MyInjectable {}

inject(['$window', MyInjectable], noop);

expect( mockInjectFn.args[0][0].$inject ).to.deep.equal(['$window', 'MyInjectable']);
});
});
});

0 comments on commit c4b11ba

Please sign in to comment.