Currently, I am working on testing a function called getSingleShip in Angular 12 using Karma-Jasmine 4. The aim is to verify if this function is being called by another function named retrieveShip. However, the test results indicate that getSingleShip has not been called at all.
I have a suspicion that the actual service is being invoked instead of the mock service. How can I properly mock the service for testing purposes?
Tests similar to the one below fail due to dependencies on mockShipsService.getSingleShip (Expected spy ShipsService.getSingleShip to have been called once. It was called 0 times.).
Here is an example code snippet from spec.ts:
// Code snippet for TestBed configuration and setup
// Test case for retrieveShip function
describe('retrieveShip', () => {
it('should call getSingleShip once', () => {
// Mock response for getSingleShip
const getSingleShipResponse = {
_id: "610a80fd485a6ad03b43b539",
name: "Sabrina",
type: "cruise"
};
mockShipsService.getSingleShip.and.returnValue(of(getSingleShipResponse));
component.retrieveShip("610a80fd485a6ad03b43b539");
expect(mockShipsService.getSingleShip).toHaveBeenCalledTimes(1);
})
})
The testing approach follows the guidelines provided in the Angular documentation available here: Testing services
For reference, here are snippets from the component.ts and service.ts files:
// Component method to retrieve ship details
retrieveShip(shipId: string): void {
this.shipsService.getSingleShip(shipId).subscribe({
next: response => {
this.ship = response;
},
error: err => this.errorMessage = err
});
}
// Service method definition to fetch single ship data
@Injectable({
providedIn: 'root'
})
export class ShipsService {
readonly ROOT_URL: string = environment.ROOT_URL;
constructor(
private http: HttpClient,
) {
}
getSingleShip(shipId: string): Observable<Ship> {
return this.http.get<Ship>(`${this.ROOT_URL}/ships/${shipId}`);
}
}
If you have any suggestions or tips on how to resolve the issue, your input would be highly appreciated!