Hi i'm trying to get into testing my components in Angular2 but have ran into an issue when i'm trying to mock my service. I'm currently following the Angular2 docs on testing.
I'm calling my backend API that i've built from the angular service, which works fine as long as I have a JWT token. But when it comes to testing, I would just like to mock the service in my component test.
Service
@Injectable()
export class ItemService {
constructor(private _http: AuthHttp, private _store: Store<AppStore>) {}
items(): Observable<any[]> {
return this._http.get(ENDPOINT_ITEMS, {withCredentials: false})
.map((response: Response) => response.json().data);
}
}
Component
@Component({
selector: 'items',
template: require('./items.component.html'),
providers: [ItemService]
})
export class ItemsComponent {
items: Observable<Array<Object>>;
constructor(private _service: ItemService) {}
ngOnInit(): any {
this.items = this._service.items();
}
}
Component test
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [ ItemsComponent ],
providers: [
{ provide: ItemService, useValue: itemsMock },
]
});
fixture = TestBed.createComponent(ItemsComponent);
itemService = fixture.debugElement.injector.get(ItemService)
I would like my mocked ItemService to return the useValue, itemsMock, for me so I can test that my html tags do have the correct data. But it doesn't look like my service is getting mocked right?
Getting this error:
Error: Error in ./ItemsComponent class ItemsComponent_Host - inline template:0:0 caused by: No provider for AuthHttp! in karma.entry.js (line 17341)
Your component has ItemService
in its providers. That means every time an instance of the component is created, a new instance of ItemService will be created for the component. The service at the module level won't be used.
Your service is stateless, and has probably no good reason to be at the component level. Remove it from the providers, and make sure it's in the providers of the module.