Using a stub to replace the dependency

Using a stub means that we completely replace what was there before. It is as simple to do as instructing the TestBed in the following way:

TestBed.configureTestingModule({
declarations: [ExampleComponent]
providers: [{
provide: DependencyService,
useClass: DependencyServiceStub
}]
});

We define a providers array like we do with the NgModule, and we give it a list item that points out the definition we intend to replace and we give it the replacement instead; that is our stub.

Let's now build our DependencyStub to look like this:

class DependencyServiceStub {
getData() { return 'stub'; }
}

Just like with an @NgModule, we are able to override the definition of our dependency with our own stub. Imagine our component looks like the following:

import { Component } from '@angular/core';
import { DependencyService } from "./dependency.service";

@Component({
selector: 'example',
template: `
<div>{{ title }}</div>
`
})
export class ExampleComponent {
title: string;

constructor(private dependency: DependencyService) {
this.title = this.dependency.getData();
}
}

Here we pass an instance of the dependency in the constructor. With our testing module correctly set up, with our stub, we can now write a test that looks like this:

it(`should have as title 'stub'`, async(() => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app.title).toEqual('stub');
}));

The test looks normal, but at the point when the dependency would be called in the component code, our stub takes its place and responds instead. Our dependency should be overridden, and as you can see, the expect(app.title).toEqual('stub') assumes the stub will answer, which it does.

..................Content has been hidden....................

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