Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

110
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda