I'm working with a TypeScript ModelService
that has an edit
function:
edit(model: Model): Observable<Model> {
const body = JSON.stringify(model);
return this.http.put(`/models/edit/${model.id}`, body));
}
Additionally, there is a TypeScript EditComponent
that contains an edit
function. This function subscribes to the service and navigates when it receives a response:
edit(model: Model): void {
this.service
.edit(model)
.subscribe(() => this.router.navigate([`/models/details/${model.id}`]);
}
What would be the most effective method for testing this component's edit
function?
A Jasmine test that I have attempts to achieve this:
// Set up
TestBed.configureTestingModule({
declarations: [EditComponent],
providers: [
{
provide: ModelService,
useValue: jasmine.createSpyObj('ModelService', ['edit'])
}
]
});
const fixture = TestBed.createComponent(EditComponent);
const component = fixture.componentInstance;
const modelService = fixture.debugElement.injector.get(ModelService);
fixture.detectChanges();
// Test
it('should call edit', () => {
fakeAsync(() => {
component.edit(model);
expect(modelService.edit).toHaveBeenCalled();
});
});
However, when running this test, I consistently receive SPEC HAS NO EXPECTATIONS
. I believed fakeAsync
ran synchronously, which led me to believe it would work.
I've also experimented with variations of async
, tick()
, and done()
, but these approaches either yield the same message or fail with
Cannot read property 'subscribe' of undefined
when attempting to call the component's edit
function.
In previous tests, I successfully used
return fixture.whenStable().then()
(as explained here), but in this case, I don't think it applies given that the component function returns void
rather than a Promise.
Could anyone provide insight on a more efficient way to test this component function?