Angular testing utilities

As you could see in the previous section, Angular comes with a testing library, @angular/core/testing, which offers the TestBed helper class and many other utilities. TestBed helps us to set up dependencies for tests--modules, components, providers, and so on. You can call TestBed.configureTestingModule() and pass the same metadata configuration object as used with @NgModule. The configureTestingModule() function should be called within a beforeEach() setup function.

Another useful function from the testing library is called inject(). It allows you to inject the specified objects into the tests. The following code snippet provides an example:

describe('MyService', () => {
let service;

beforeEach(() => TestBed.configureTestingModule({
providers: [MyService]
}));

beforeEach(inject([MyService], s => {
service = s;
}));

it('should return the city Bern', () => {
expect(service.getCities()).toContain('Bern');
});
});

The next useful function is the async() function. It may be used with asynchronous operations because it doesn't complete the test until all asynchronous operations in the test have been completed or the specified timeout occurs. The async() function wraps the second argument of the it() function:

it('do something', async(() => {
// make asynchronous operation here, e.g. call a REST service
}), 3000));

The timeout parameter is optional. It is also possible to call async() in combination with inject():

it('do something', async(inject([SomeService], s => {
...
})));
Note that if you change some component's property value and this property is bound to the view via the ngModel directive, you have to do this within async() as well. The reason: ngModel updates the value asynchronously. We will develop an appropriate example in this section.

The fakeAsync() function from the Angular testing utilities is similar to async(), but it enables a linear coding style by running the test body in a special fakeAsync test zone. The fakeAsync() method is used in combination with the tick() function, which simulates the passage of time until all pending asynchronous activities have been finished. There are no nested then(...) blocks anymore; the test appears to be synchronous:

changeSomethingAsync1();
...
tick();
expect(something).toBeDefined();

changeSomethingAsync2();
...
tick();
expect(something).toBeNull();
There is one limitation with fakeAsync()--you cannot make an XHR call from within fakeAsync().
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.227.111.197