You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
feat(ngMock): add sharedInjector() to angular.mock.module
Allow to opt-in to using a shared injector within a context. This allows hooks to be
used in Jasmine 2.x.x/Mocha
Closesangular#14093Closesangular#10238
Copy file name to clipboardExpand all lines: docs/content/guide/unit-testing.ngdoc
+37
Original file line number
Diff line number
Diff line change
@@ -438,5 +438,42 @@ In tests, you can trigger a digest by calling a scope's {@link ng.$rootScope.Sco
438
438
If you don't have a scope in your test, you can inject the {@link ng.$rootScope $rootScope} and call `$apply` on it.
439
439
There is also an example of testing promises in the {@link ng.$q#testing `$q` service documentation}.
440
440
441
+
## Using `beforeAll()`
442
+
443
+
Jasmine's `beforeAll()` and mocha's `before()` hooks are often useful for sharing test setup - either to reduce test run-time or simply to make for more focussed test cases.
444
+
445
+
By default, ngMock will create an injector per test case to ensure your tests do not affect each other. However, if we want to use `beforeAll()`, ngMock will have to create the injector before any test cases are run, and share that injector through all the cases for that `describe`. That is where {@link angular.mock.module.sharedInjector module.sharedInjector()} comes in. When it's called within a `describe` block, a single injector is shared between all hooks and test cases run in that block.
446
+
447
+
In the example below we are testing a service that takes a long time to generate its answer. To avoid having all of the assertions we want to write in a single test case, {@link angular.mock.module.sharedInjector module.sharedInjector()} and Jasmine's `beforeAll()` are used to run the service only one. The test cases then all make assertions about the properties added to the service instance.
448
+
449
+
```javascript
450
+
describe("Deep Thought", function() {
451
+
452
+
module.sharedInjector();
453
+
454
+
beforeAll(module("UltimateQuestion"));
455
+
456
+
beforeAll(inject(function(DeepThought) {
457
+
expect(DeepThought.answer).toBe(undefined);
458
+
DeepThought.generateAnswer();
459
+
}));
460
+
461
+
it("has calculated the answer correctly", inject(function(DeepThought) {
462
+
// Because of sharedInjector, we have access to the instance of the DeepThought service
463
+
// that was provided to the beforeAll() hook. Therefore we can test the generated answer
464
+
expect(DeepThought.answer).toBe(42);
465
+
}));
466
+
467
+
it("has calculated the answer within the expected time", inject(function(DeepThought) {
0 commit comments