I am facing an issue with a service method that performs an HTTP delete operation. The expected behavior is that upon successful deletion, the page should be redirected to another location. However, during testing, I noticed that the router navigation function is not being called as expected. This resulted in a failure report generated by Jasmine:
Jasmine spec failure test:
Service: MemberDelete > Testing deleteMember() succesfully
Expected spy navigate to have been called with:
[ [ '/members' ] ]
but it was never called.
The code snippet from my testing file member-delete.service.spec.ts is as follows:
import { HttpClient, HttpResponse} from '@angular/common/http';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { TestBed, async, inject } from '@angular/core/testing';
import { Router } from '@angular/router';
import { RouterTestingModule } from '@angular/router/testing';
import { memberMockObject } from 'src/app/components/member/member.mocks';
import {createSpyFromClass, Spy} from 'jasmine-auto-spies';
import { MemberDeleteService } from './member-delete.service';
import { environment } from '../../../environments/environment';
describe('Service: MemberDelete', () => {
let service: MemberDeleteService;
let mockHttp: HttpClientTestingModule;
let mockHttpTestingController: HttpTestingController;
let router: Router;
beforeEach(() => {
TestBed.configureTestingModule({
imports:[
HttpClientTestingModule,
RouterTestingModule
],
providers:[
{ provider: MemberDeleteService, useValue: service },
{ provider: HttpClient, useValue: createSpyFromClass(HttpClient) }
]
});
mockHttp = TestBed.inject(HttpClient);
mockHttpTestingController = TestBed.inject(HttpTestingController);
service = TestBed.inject(MemberDeleteService);
router = TestBed.inject(Router);
});
afterEach(() => {
mockHttpTestingController.verify(); //Verifies that no requests are outstanding.
});
it('should ...', () => {
expect(service).toBeTruthy();
});
it('Testing deleteMember() succesfully', () => {
spyOn(router, 'navigate');
service.deleteMember(memberMockObject.fakeMember.id);
expect(router.navigate).toHaveBeenCalledWith(['/members']);
});
});
The relevant service method from member-delete.service.ts can be found below:
public deleteMember(memberId: number): void {
this._http.delete(`${this._membersUrl}/${memberId}`).subscribe({
complete: () => {
this.router.navigate(
[`/members`]
);
},
error: (error) => {this.handleError(error);}
});
}
Your assistance in resolving this issue would be greatly appreciated. Thank you for your help.