Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

111
Vistas
Test code changes in function after promise resolved with .then using Jest

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?

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda