I have a service set up like so:
export class ExampleService {
exampleConfig : Promise<any> = undefined;
constructor(private _http: HttpClient) {
const headers = {
headers: new HttpHeaders({'Cache-Control: 'no-store, no-cache, max-age=0', 'Pragma': 'no-cache', 'Expires': '0'})
};
this.exampleConfig = _http.get("ui-conf.json", headers).toPromise();
}
exampleFunction() {
this.exampleConfig.then((config) => {
window.location.href = "https://"+config.api+"/examplePath";
}).catch{(reason) => {
window.location.href = "https://" + window.location.hostname + "/failurePath";
});
}
}
I'm trying to test this service using Jest, so I have spec file set up like so:
describe('ExampleService', () => {
let service: ExampleService;
let httpMock: HttpClient;
let testConfig = {
"api": "local.testSite.com"
}
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientModule, HttpClientTestingModule],
providers: [ExampleService]
});
service = TestBed.inject(ExampleService)
httpMock = TestBed.inject(HttpClient)
});
it('this is my test', async () => {
const httpSpy = jest.spyOn(httpMock, 'get')
.mockImplementationOnce(() => of(testConfig))
await service.exampleFunction();
expect(window.location.href).toEqual("https://local.testSite.com/examplePath")
})
});
The ui-conf.json file is literally just an object that looks similar to how I set it in the testConfig object in the spec file. When I run this code, the test fails because window.location.href was never changed. If I put a console.log in the Example function before exampleConfig.then is called, I can see the log output, but if I put a console log within the .then piece, I don't see it at all. If I set any other values in .then, they are never changed when I test those values in my spec file. It's like the code within exampleConfig.then is never reached, so how do I get there to test the function correctly to make sure it's setting things properly?