Reputation: 439
I'm trying to learn how to run a unit test component on angular 4, but I'm not getting success, when I run the test with the code below I get this error:
Error: No provider for http! and Failed: : could not find an object to spy upon for filexGeneralData()
I don't know if I'm on the right way...
Take a look at my code
my spec file
import { TestBed, async, inject } from '@angular/core/testing';
import { HttpModule } from '@angular/http';
import { of } from 'rxjs/observable/of';
import { filex } from '../../../models/filex';
import { filexService } from '../../../services/filex.service';
import { fileyfilexComponent } from './filey-filex.component';
import { dataService } from '../../../services/data.service';
describe('fileyfilexComponent', () => {
let filexService;
let myComponent;
let fixture;
let element;
beforeEach(
async(() => {
TestBed.configureTestingModule({
declarations: [fileyfilexComponent],
providers: [filexService, dataService],
imports: [HttpModule]
}).compileComponents();
})
);
beforeEach(inject([filexService], s => {
filexService = s;
fixture = TestBed.createComponent(fileyfilexComponent);
myComponent = fixture.componentInstance;
element = fixture.nativeElement;
}));
it(
'should call getUsers and return list of users',
async(() => {
const response: filex[] = [];
spyOn(filexService, 'filexGeneralData').and.returnValue(of(response));
myComponent.method1();
fixture.detectChanges();
expect(myComponent.datafilex).toEqual(response);
})
);
});
Upvotes: 2
Views: 5981
Reputation: 8306
You just need to include HubWrapperComponent
in your TestBed
. In the providers
array, you need to include all of the services provided to your component being tested (better yet, you should provide "mocked" versions of those service). So, you could get the error to "go away" by simply adding HubWrapperComponent
to the providers
array in your spec
file's TestBed.configureTestingModule
method. It will end up looking like this:
spec.ts:
TestBed.configureTestingModule({
declarations: [IndicatorsDashboardComponent],
providers: [DashboardService, DadosService, HubWrapperComponent],
imports: [HttpModule]
}).compileComponents();
An additional piece of advice: I would advise using jasmine to mock your HubWrapperComponent
(which seems to be a wrapper over the HttpClient
?).
mockWrapper = jasmine.createSpyObj('http', ['get']);
Then in your providers
array:
{provide: HubWrapperComponent, useValue: mockWrapper}
That approach would look something like this:
let mockHub: SpyObj<HubWrapperComponent>;
beforeEach(
async(() => {
mockHub = jasmine.createSpyObj('http', ['get']);
TestBed.configureTestingModule({
declarations: [IndicatorsDashboardComponent],
providers: [
DashboardService,
DadosService,
{ provide: HubWrapperComponent, useValue: mockHub }
],
imports: [HttpModule]
}).compileComponents();
})
);
Mocking a service / anything that makes Http
calls is preferred because you don't want to make real requests in your tests.
Upvotes: 5