Tengo un servicio configurado así:
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"; }); } }Estoy tratando de probar este servicio usando Jest, así que tengo un archivo de especificaciones configurado así:
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") }) });El archivo ui-conf.json es literalmente solo un objeto que se parece a cómo lo configuré en el objeto testConfig en el archivo de especificaciones. Cuando ejecuto este código, la prueba falla porque window.location.href nunca se modificó. Si coloco un archivo console.log en la función Example antes de que se llame a exampleConfig.then, puedo ver la salida del registro, pero si coloco un registro de la consola dentro de la pieza .then, no lo veo en absoluto. Si configuro otros valores en .then, nunca se cambian cuando pruebo esos valores en mi archivo de especificaciones. Es como si nunca se llegara al código dentro de exampleConfig.then, entonces, ¿cómo llego allí para probar la función correctamente y asegurarme de que está configurando las cosas correctamente?