Currently, I am working on an Angular 5 Project, but it's not a major project. However, I haven't been involved in the Angular2+ environment since early 2.1/2.2.
My issue revolves around a Service that makes a call to a public API. Unfortunately, my test is failing with the error message:
Error: Expected one matching request for criteria "Match URL: http://api.icndb.com/jokes/random/10", found none.
Here is the code snippet:
fact.service.spec.ts
import {HttpClientTestingModule, HttpTestingController} from "@angular/common/http/testing";
import {TestBed, inject} from "@angular/core/testing";
import {FactService} from "./fact.service";
import {Fact} from "../models/fact";
import {FactHttpResponse} from "../models/factHttpResponse";
describe("FactService", () => {
let factService: FactService;
let httpMock: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [FactService],
});
httpMock = TestBed.get(HttpTestingController);
factService = TestBed.get(FactService);
});
// TODO: There seems to be an issue with this test, seeking online help
it("Should be able to retrieve Facts in subscription when calling loadFacts", (done) => {
const factList: Fact[] = [
{id: 1, joke: "a"},
{id: 2, joke: "a"},
];
const factResponse: FactHttpResponse = { value: factList};
factService.subscribe(val => {
expect(val).toEqual(factList);
done();
});
const mockRequest = httpMock
.expectOne(factService.CHUCK_NORRIS_API.replace("{count}", "10"));
expect(mockRequest.request.method).toEqual('GET');
factService.loadFacts();
mockRequest.flush(factResponse);
});
afterEach(inject([HttpTestingController], (httpMock: HttpTestingController) => {
httpMock.verify();
}));
});
fact.service.ts
import { HttpClient } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Subject } from "rxjs/Subject";
import {Fact} from "../models/fact";
import {FactHttpResponse} from "../models/factHttpResponse";
@Injectable()
export class FactService {
// public for testing purposes
public readonly CHUCK_NORRIS_API = "http://api.icndb.com/jokes/random/{count}";
private factSubject = new Subject();
private facts: Fact[] = [];
private favorites: Fact[] = [];
constructor(private http: HttpClient) { }
public subscribe(callback: (value: Fact[]) => void) {
return this.factSubject.subscribe(callback);
}
public loadFacts(count = 10) {
this.http.get<FactHttpResponse>(this.CHUCK_NORRIS_API.replace("{count}", count.toString()))
.subscribe(data => {
if (data.value) {
this.facts = data.value
.map(f => {
f.favorite = !!this.favorites.find(fav => fav.id === f.id);
return f;
});
this.factSubject.next(this.facts);
}
});
}
}
The code is functioning properly, but I am encountering difficulties in testing it. Interestingly, removing the verifyOne line results in a complaint about an outstanding request to the exact same URL mentioned in the error message.