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

161
Views
Expect error to be thrown out of next handler of observable, testing Angular with Jasmine

In Angular application have a controller with following method

onClick(): void {
    this.http
        .get('some/endpoint')
        .subscribe(
            (response) => {
                const editUrl = this.service.composeUrl(response);

                if (!editUrl) {
                    // want to test this error is thrown, when editUrl is null
                    throw Error('Cannot construct valid URL');
                }

                // do something else
            },
            () => {
                // request clean up
            }
        );
}

I would like to write Jasmine test to verify, that if the editUrl cannot be composed out of response an error will be thrown.

it('when call is successful but editUrl cannot be constructed, then error is thrown', () => {
    mockHttp.get = jasmine
            .createSpy()
            .and.returnValue(of({}));


    mockService.composeUrl= jasmine
            .createSpy()
            .and.returnValue(null);

    expect(() => { component.onClick() }).toThrowError();
});

My test fails with:

Error: Expected function to throw an Error.

But I also see in the browser console, that the error was thrown Uncaught Error: Cannot construct valid URL

I think the problem is in that Error is thrown in the next handler of http observable, and that's somehow running out of jasmine context.

I could fix it by extracting anonymous next handler into named function and test directly that function, but I prefer having subscribe with anonymous arrow functions.

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!