feat(test): add withProviders for per test providers

Closes #5128
This commit is contained in:
Julie Ralph 2015-12-10 12:00:48 -08:00 committed by Matias Niemela
parent c6afea61f1
commit c1a0af514f
2 changed files with 34 additions and 1 deletions

View File

@ -36,6 +36,10 @@ export class TestInjector {
}
execute(fn: FunctionWithParamTokens): any {
var additionalProviders = fn.additionalProviders();
if (additionalProviders.length > 0) {
this.addProviders(additionalProviders);
}
if (!this._instantiated) {
this.createInjector();
}
@ -119,6 +123,22 @@ export function inject(tokens: any[], fn: Function): FunctionWithParamTokens {
return new FunctionWithParamTokens(tokens, fn, false);
}
export class InjectSetupWrapper {
constructor(private _providers: () => any) {}
inject(tokens: any[], fn: Function): FunctionWithParamTokens {
return new FunctionWithParamTokens(tokens, fn, false, this._providers);
}
injectAsync(tokens: any[], fn: Function): FunctionWithParamTokens {
return new FunctionWithParamTokens(tokens, fn, true, this._providers);
}
}
export function withProviders(providers: () => any) {
return new InjectSetupWrapper(providers);
}
/**
* Allows injecting dependencies in `beforeEach()` and `it()`. The test must return
* a promise which will resolve when all asynchronous activity is complete.
@ -141,8 +161,13 @@ export function injectAsync(tokens: any[], fn: Function): FunctionWithParamToken
return new FunctionWithParamTokens(tokens, fn, true);
}
function emptyArray(): Array<any> {
return [];
}
export class FunctionWithParamTokens {
constructor(private _tokens: any[], private _fn: Function, public isAsync: boolean) {}
constructor(private _tokens: any[], private _fn: Function, public isAsync: boolean,
public additionalProviders: () => any = emptyArray) {}
/**
* Returns the value of the executed function.

View File

@ -10,6 +10,7 @@ import {
beforeEach,
inject,
injectAsync,
withProviders,
beforeEachProviders,
TestComponentBuilder
} from 'angular2/testing';
@ -186,6 +187,13 @@ export function main() {
inject([FancyService], (service) => { expect(service.value).toEqual('async value'); }));
});
});
describe('per test providers', () => {
it('should allow per test providers',
withProviders(() => [bind(FancyService).toValue(new FancyService())])
.inject([FancyService],
(service) => { expect(service.value).toEqual('real value'); }));
});
});
describe('errors', () => {