X Tutup
Skip to content

Commit b803ecf

Browse files
committed
refactor(testing): reenable injectAsync checking for return value
Before angular#5375, injectAsync would check the return value and fail if it was not a promise, to help users remember that they need to return a promise from an async test. angular#5375 removed that with the introduction of the testing zone. This un-deprecates `injectAsync` until we can resolve angular#5515. To be clear, this means that `inject` and `injectAsync` are now identical except that `injectAsync` will fail if the test does not return a promise, and `inject` will fail if the test returns any value. Closes angular#5721
1 parent d3a79db commit b803ecf

File tree

3 files changed

+144
-39
lines changed

3 files changed

+144
-39
lines changed

modules/angular2/src/testing/test_injector.ts

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -142,9 +142,7 @@ export function createTestInjectorWithRuntimeCompiler(
142142
}
143143

144144
/**
145-
* Allows injecting dependencies in `beforeEach()` and `it()`. When using with the
146-
* `angular2/testing` library, the test function will be run within a zone and will
147-
* automatically complete when all asynchronous tests have finished.
145+
* Allows injecting dependencies in `beforeEach()` and `it()`.
148146
*
149147
* Example:
150148
*
@@ -155,9 +153,8 @@ export function createTestInjectorWithRuntimeCompiler(
155153
* }));
156154
*
157155
* it('...', inject([AClass], (object) => {
158-
* object.doSomething().then(() => {
159-
* expect(...);
160-
* });
156+
* object.doSomething();
157+
* expect(...);
161158
* })
162159
* ```
163160
*
@@ -174,7 +171,22 @@ export function inject(tokens: any[], fn: Function): FunctionWithParamTokens {
174171
}
175172

176173
/**
177-
* @deprecated Use inject instead, which now supports both synchronous and asynchronous tests.
174+
* Allows injecting dependencies in `beforeEach()` and `it()`. The test must return
175+
* a promise which will resolve when all asynchronous activity is complete.
176+
*
177+
* Example:
178+
*
179+
* ```
180+
* it('...', injectAsync([AClass], (object) => {
181+
* return object.doSomething().then(() => {
182+
* expect(...);
183+
* });
184+
* })
185+
* ```
186+
*
187+
* @param {Array} tokens
188+
* @param {Function} fn
189+
* @return {FunctionWithParamTokens}
178190
*/
179191
export function injectAsync(tokens: any[], fn: Function): FunctionWithParamTokens {
180192
return new FunctionWithParamTokens(tokens, fn, true);

modules/angular2/src/testing/testing.ts

Lines changed: 39 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -192,9 +192,26 @@ function _it(jsmFn: Function, name: string, testFn: FunctionWithParamTokens | An
192192
injector = createTestInjectorWithRuntimeCompiler(testProviders);
193193
}
194194

195-
var returnedTestValue = runInTestZone(() => testFn.execute(injector), done, done.fail);
196-
if (_isPromiseLike(returnedTestValue)) {
197-
(<Promise<any>>returnedTestValue).then(null, (err) => { done.fail(err); });
195+
var finishCallback = () => {
196+
// Wait one more event loop to make sure we catch unreturned promises and
197+
// promise rejections.
198+
setTimeout(done, 0);
199+
};
200+
var returnedTestValue =
201+
runInTestZone(() => testFn.execute(injector), finishCallback, done.fail);
202+
203+
if (testFn.isAsync) {
204+
if (_isPromiseLike(returnedTestValue)) {
205+
(<Promise<any>>returnedTestValue).then(null, (err) => { done.fail(err); });
206+
} else {
207+
done.fail('Error: injectAsync was expected to return a promise, but the ' +
208+
' returned value was: ' + returnedTestValue);
209+
}
210+
} else {
211+
if (!(returnedTestValue === undefined)) {
212+
done.fail('Error: inject returned a value. Did you mean to use injectAsync? Returned ' +
213+
'value was: ' + returnedTestValue);
214+
}
198215
}
199216
}, timeOut);
200217
} else {
@@ -220,13 +237,30 @@ export function beforeEach(fn: FunctionWithParamTokens | AnyTestFn): void {
220237
if (fn instanceof FunctionWithParamTokens) {
221238
// The test case uses inject(). ie `beforeEach(inject([ClassA], (a) => { ...
222239
// }));`
223-
224240
jsmBeforeEach((done) => {
241+
var finishCallback = () => {
242+
// Wait one more event loop to make sure we catch unreturned promises and
243+
// promise rejections.
244+
setTimeout(done, 0);
245+
};
225246
if (!injector) {
226247
injector = createTestInjectorWithRuntimeCompiler(testProviders);
227248
}
228249

229-
runInTestZone(() => fn.execute(injector), done, done.fail);
250+
var returnedTestValue = runInTestZone(() => fn.execute(injector), finishCallback, done.fail);
251+
if (fn.isAsync) {
252+
if (_isPromiseLike(returnedTestValue)) {
253+
(<Promise<any>>returnedTestValue).then(null, (err) => { done.fail(err); });
254+
} else {
255+
done.fail('Error: injectAsync was expected to return a promise, but the ' +
256+
' returned value was: ' + returnedTestValue);
257+
}
258+
} else {
259+
if (!(returnedTestValue === undefined)) {
260+
done.fail('Error: inject returned a value. Did you mean to use injectAsync? Returned ' +
261+
'value was: ' + returnedTestValue);
262+
}
263+
}
230264
});
231265
} else {
232266
// The test case doesn't use inject(). ie `beforeEach((done) => { ... }));`

modules/angular2/test/testing/testing_public_spec.ts

Lines changed: 86 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import {
99
tick,
1010
beforeEach,
1111
inject,
12+
injectAsync,
1213
beforeEachProviders,
1314
TestComponentBuilder
1415
} from 'angular2/testing';
@@ -153,8 +154,9 @@ export function main() {
153154
it('should use set up providers',
154155
inject([FancyService], (service) => { expect(service.value).toEqual('real value'); }));
155156

156-
it('should wait until returned promises', inject([FancyService], (service) => {
157-
service.getAsyncValue().then((value) => { expect(value).toEqual('async value'); });
157+
it('should wait until returned promises', injectAsync([FancyService], (service) => {
158+
return service.getAsyncValue().then(
159+
(value) => { expect(value).toEqual('async value'); });
158160
}));
159161

160162
describe('using beforeEach', () => {
@@ -167,8 +169,8 @@ export function main() {
167169
});
168170

169171
describe('using async beforeEach', () => {
170-
beforeEach(inject([FancyService], (service) => {
171-
service.getAsyncValue().then((value) => { service.value = value; });
172+
beforeEach(injectAsync([FancyService], (service) => {
173+
return service.getAsyncValue().then((value) => { service.value = value; });
172174
}));
173175

174176
it('should use asynchronously modified value',
@@ -196,18 +198,70 @@ export function main() {
196198
var restoreJasmineIt = () => { jasmine.getEnv().it = originalJasmineIt; };
197199

198200
var patchJasmineBeforeEach = () => {
201+
var deferred = PromiseWrapper.completer();
199202
originalJasmineBeforeEach = jasmine.getEnv().beforeEach;
200203
jasmine.getEnv().beforeEach = (fn: any) => {
201-
var done = () => {};
202-
(<any>done).fail = (err) => { throw new Error(err) };
204+
var done = () => { deferred.resolve() };
205+
(<any>done).fail = (err) => { deferred.reject(err) };
203206
fn(done);
204207
return null;
205-
}
208+
};
209+
return deferred.promise;
206210
};
207211

208212
var restoreJasmineBeforeEach =
209213
() => { jasmine.getEnv().beforeEach = originalJasmineBeforeEach; }
210214

215+
it('injectAsync should fail when return was forgotten in it', (done) => {
216+
var itPromise = patchJasmineIt();
217+
it('forgets to return a proimse', injectAsync([], () => { return true; }));
218+
219+
itPromise.then(() => { done.fail('Expected function to throw, but it did not'); }, (err) => {
220+
expect(err).toEqual(
221+
'Error: injectAsync was expected to return a promise, but the returned value was: true');
222+
done();
223+
});
224+
restoreJasmineIt();
225+
});
226+
227+
it('inject should fail if a value was returned', (done) => {
228+
var itPromise = patchJasmineIt();
229+
it('returns a value', inject([], () => { return true; }));
230+
231+
itPromise.then(() => { done.fail('Expected function to throw, but it did not'); }, (err) => {
232+
expect(err).toEqual(
233+
'Error: inject returned a value. Did you mean to use injectAsync? Returned value was: true');
234+
done();
235+
});
236+
restoreJasmineIt();
237+
});
238+
239+
it('injectAsync should fail when return was forgotten in beforeEach', (done) => {
240+
var beforeEachPromise = patchJasmineBeforeEach();
241+
beforeEach(injectAsync([], () => { return true; }));
242+
243+
beforeEachPromise.then(
244+
() => { done.fail('Expected function to throw, but it did not'); }, (err) => {
245+
expect(err).toEqual(
246+
'Error: injectAsync was expected to return a promise, but the returned value was: true');
247+
done();
248+
});
249+
restoreJasmineBeforeEach();
250+
});
251+
252+
it('inject should fail if a value was returned in beforeEach', (done) => {
253+
var beforeEachPromise = patchJasmineBeforeEach();
254+
beforeEach(inject([], () => { return true; }));
255+
256+
beforeEachPromise.then(
257+
() => { done.fail('Expected function to throw, but it did not'); }, (err) => {
258+
expect(err).toEqual(
259+
'Error: inject returned a value. Did you mean to use injectAsync? Returned value was: true');
260+
done();
261+
});
262+
restoreJasmineBeforeEach();
263+
});
264+
211265
it('should fail when an error occurs inside inject', (done) => {
212266
var itPromise = patchJasmineIt();
213267
it('throws an error', inject([], () => { throw new Error('foo'); }));
@@ -235,7 +289,7 @@ export function main() {
235289
it('should fail when a returned promise is rejected', (done) => {
236290
var itPromise = patchJasmineIt();
237291

238-
it('should fail with an error from a promise', inject([], () => {
292+
it('should fail with an error from a promise', injectAsync([], () => {
239293
var deferred = PromiseWrapper.completer();
240294
var p = deferred.promise.then(() => { expect(1).toEqual(2); });
241295

@@ -259,8 +313,8 @@ export function main() {
259313
describe('nested beforeEachProviders', () => {
260314

261315
it('should fail when the injector has already been used', () => {
316+
patchJasmineBeforeEach();
262317
expect(() => {
263-
patchJasmineBeforeEach();
264318
beforeEachProviders(() => [bind(FancyService).toValue(new FancyService())]);
265319
})
266320
.toThrowError('beforeEachProviders was called after the injector had been used ' +
@@ -273,19 +327,19 @@ export function main() {
273327

274328
describe('test component builder', function() {
275329
it('should instantiate a component with valid DOM',
276-
inject([TestComponentBuilder], (tcb: TestComponentBuilder) => {
330+
injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) => {
277331

278-
tcb.createAsync(ChildComp).then((componentFixture) => {
332+
return tcb.createAsync(ChildComp).then((componentFixture) => {
279333
componentFixture.detectChanges();
280334

281335
expect(componentFixture.debugElement.nativeElement).toHaveText('Original Child');
282336
});
283337
}));
284338

285339
it('should allow changing members of the component',
286-
inject([TestComponentBuilder], (tcb: TestComponentBuilder) => {
340+
injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) => {
287341

288-
tcb.createAsync(MyIfComp).then((componentFixture) => {
342+
return tcb.createAsync(MyIfComp).then((componentFixture) => {
289343
componentFixture.detectChanges();
290344
expect(componentFixture.debugElement.nativeElement).toHaveText('MyIf()');
291345

@@ -295,9 +349,10 @@ export function main() {
295349
});
296350
}));
297351

298-
it('should override a template', inject([TestComponentBuilder], (tcb: TestComponentBuilder) => {
352+
it('should override a template',
353+
injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) => {
299354

300-
tcb.overrideTemplate(MockChildComp, '<span>Mock</span>')
355+
return tcb.overrideTemplate(MockChildComp, '<span>Mock</span>')
301356
.createAsync(MockChildComp)
302357
.then((componentFixture) => {
303358
componentFixture.detectChanges();
@@ -306,10 +361,12 @@ export function main() {
306361
});
307362
}));
308363

309-
it('should override a view', inject([TestComponentBuilder], (tcb: TestComponentBuilder) => {
364+
it('should override a view',
365+
injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) => {
310366

311-
tcb.overrideView(ChildComp,
312-
new ViewMetadata({template: '<span>Modified {{childBinding}}</span>'}))
367+
return tcb.overrideView(
368+
ChildComp,
369+
new ViewMetadata({template: '<span>Modified {{childBinding}}</span>'}))
313370
.createAsync(ChildComp)
314371
.then((componentFixture) => {
315372
componentFixture.detectChanges();
@@ -319,9 +376,9 @@ export function main() {
319376
}));
320377

321378
it('should override component dependencies',
322-
inject([TestComponentBuilder], (tcb: TestComponentBuilder) => {
379+
injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) => {
323380

324-
tcb.overrideDirective(ParentComp, ChildComp, MockChildComp)
381+
return tcb.overrideDirective(ParentComp, ChildComp, MockChildComp)
325382
.createAsync(ParentComp)
326383
.then((componentFixture) => {
327384
componentFixture.detectChanges();
@@ -332,9 +389,9 @@ export function main() {
332389

333390

334391
it("should override child component's dependencies",
335-
inject([TestComponentBuilder], (tcb: TestComponentBuilder) => {
392+
injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) => {
336393

337-
tcb.overrideDirective(ParentComp, ChildComp, ChildWithChildComp)
394+
return tcb.overrideDirective(ParentComp, ChildComp, ChildWithChildComp)
338395
.overrideDirective(ChildWithChildComp, ChildChildComp, MockChildChildComp)
339396
.createAsync(ParentComp)
340397
.then((componentFixture) => {
@@ -345,9 +402,11 @@ export function main() {
345402
});
346403
}));
347404

348-
it('should override a provider', inject([TestComponentBuilder], (tcb: TestComponentBuilder) => {
405+
it('should override a provider',
406+
injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) => {
349407

350-
tcb.overrideProviders(TestProvidersComp, [bind(FancyService).toClass(MockFancyService)])
408+
return tcb.overrideProviders(TestProvidersComp,
409+
[bind(FancyService).toClass(MockFancyService)])
351410
.createAsync(TestProvidersComp)
352411
.then((componentFixture) => {
353412
componentFixture.detectChanges();
@@ -358,10 +417,10 @@ export function main() {
358417

359418

360419
it('should override a viewProvider',
361-
inject([TestComponentBuilder], (tcb: TestComponentBuilder) => {
420+
injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) => {
362421

363-
tcb.overrideViewProviders(TestViewProvidersComp,
364-
[bind(FancyService).toClass(MockFancyService)])
422+
return tcb.overrideViewProviders(TestViewProvidersComp,
423+
[bind(FancyService).toClass(MockFancyService)])
365424
.createAsync(TestViewProvidersComp)
366425
.then((componentFixture) => {
367426
componentFixture.detectChanges();

0 commit comments

Comments
 (0)
X Tutup