Reputation: 9229
I have an angular-cli project with the following test suite:
let fakeCellService = {
getCellOEE: function (value): Observable<Array<IOee>> {
return Observable.of([{ time: moment(), val: 67 }, { time: moment(), val: 78 }]);
}
};
describe('Oee24Component', () => {
let component: any;
let fixture: ComponentFixture<Oee24Component>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [Oee24Component],
providers: [{ provide: CellService, useValue: fakeCellService }]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(Oee24Component);
component = fixture.componentInstance;
fixture.detectChanges();
spyOn(fakeCellService, 'getCellOEE');
});
it('should get cell oee on init', () => {
component.ngOnInit();
expect(fakeCellService.getCellOEE).toHaveBeenCalled();
});
});
However, the Spy in the test fails. I know the function is called, as I tested this in a debugger. I can't see how this differs from the documented examples, but presumably it does! Any ideas why?
Here is my component:
@Component({
selector: 'app-oee',
templateUrl: './oee.component.html',
styleUrls: ['./oee.component.css']
})
export class Oee24Component implements OnInit {
constructor(public dataService: CellService) { }
ngOnInit() {
this.dataService.getCellOEE(this.cell).subscribe(value => this.updateChart(value));
}
updateChart(data: Array<IOee>) {
//Logic here
}
}
Upvotes: 0
Views: 1524
Reputation: 2905
First inject the Injector
import { Injector } from '@angular/core';
import { getTestBed } from '@angular/core/testing';
Create service variable (below your component variable )
let service : CellService;
let injector : Injector;
Inject it after testbed process ( just below your component instance)
injector = getTestBed();
service = injector.get(CellService)
Now you can spy it
spyOn(service, 'YourMethod').and.returnValue({ subscribe: () => {} });
Let me know if any confusion here is your working describe section code
describe('Oee24Component', () => {
let component: any;
let fixture: ComponentFixture<Oee24Component>;
let injector: Injector;
let service: CellService;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [Oee24Component],
providers: [{ provide: CellService, useValue: fakeCellService }]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(Oee24Component);
component = fixture.componentInstance;
injector = getTestBed();
service = injector.get(CellService)
fixture.detectChanges();
spyOn(service, 'getCellOEE').and.returnValue({ subscribe : () => {} });
});
it('should get cell oee on init', () => {
component.ngOnInit();
expect(service.getCellOEE).toHaveBeenCalled();
});
});
Upvotes: 1