Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

109
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!