I want to test a simple component that have some Dependencies. So among others I have to provide some providers.
/* tslint:disable:no-unused-variable */
import { By } from '@angular/platform-browser';
import { DebugElement, provide } from '@angular/core';
import {
beforeEach,
beforeEachProviders,
describe,
expect,
it,
inject,
fakeAsync,
TestComponentBuilder
} from '@angular/core/testing';
import { AuthHttp, AuthConfig } from 'angular2-jwt';
import { Router, provideRouter } from '@angular/router';
import { Http, ConnectionBackend, RequestOptions, HTTP_PROVIDERS } from '@angular/http';
import { LogoutButtonComponent } from './logout-button.component';
import { UserService } from '../../services/index';
describe('Component: LogoutButtonComponent', () => {
let component: LogoutButtonComponent;
beforeEachProviders(() => [
LogoutButtonComponent,
Http,
provide(AuthHttp, { useFactory: Http }),
provide(AuthConfig, { useValue: new AuthConfig() }),
ConnectionBackend,
RequestOptions,
UserService
]);
beforeEach(inject([AuthHttp, UserService, LogoutButtonComponent],
(comp: LogoutButtonComponent) => {
component = comp;
}));
it('should inject UserService', () => {
// My test here
});
});
Though I'm getting the following error:
Error: Cannot resolve all parameters for 'RequestOptions'(?). Make sure that all the parameters are decorated with Inject or have valid type annotations and that 'RequestOptions' is decorated with Injectable.
Am I missing something oin the beforeEachProviders
function?
Note: This question is related only with the Unit Testing of Angular 2 with Jasmine. I'm not searching infos relate bootstraping app as this is already ok in my app and there are other related questions here.
You have to import HttpModule
into your TestBed configuration.
import { HttpModule } from "@angular/http";
TestBed.configureTestingModule({
imports: [
HttpModule
]
});
After that unit testing should work 👌🏻
RequestOptions
is not an injectable, you don't inject this into classes. Instead, you instantiate one as needed when making an HTTP request. So you can remove it from the beforeEachProviders
, and instantiate one in the beforeEach
if you actually need it in the tests:
let options: RequestOptions;
beforeEach(inject([AuthHttp, UserService, LogoutButtonComponent],
(comp: LogoutButtonComponent) => {
component = comp;
options = new RequestOptions({method: RequestMethod.Post});
}));
I've fixed my error by importing HttpModule
and Http
from @angular/http
:
import {HttpModule, Http} from "@angular/http";
...
TestBed.configureTestingModule({
imports: [HttpModule], // <!-- HTTP module
providers: [HttpService, SourceService, Http] // <!-- HTTP
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With