0

I am still coming up to speed on Angular. I searched and found very little. Most helpful was: How to write a test which expects an Error to be thrown in Jasmine?

Here is my issue after reading the above post.

I am unit testing a method that throws an error. I want to catch the error so that I know that the unit test was successful. Here is my function call:

        expect(function(){instance.selectMember(event);}).toThrow();

and the line generating the error:

        throw new Error('member not found: ' + member.id);

What I got was as follows

Expected function to throw an Error.

Followed by:

Failed: member not found: 42
Error: member not found: 42

So it failed because it didn't get an error, but then displayed the error???

I've also tried:

        expect(function(){instance.selectMember(event);}).toThrow(new Error('member not found: 42'));

and

        expect(function(){instance.selectMember(event);}).toThrowError('member not found: 42');

with the same results.

How do I know my unit test triggered the error correctly?

halfer
  • 19,824
  • 17
  • 99
  • 186
Thom
  • 14,013
  • 25
  • 105
  • 185
  • can you post the selectMember() code? Is there any async work done in it? – Ismail Oct 04 '19 at 15:08
  • 1
    @Ismail Ah, async work. Yes. That's the problem. Thanks for the input. Please post as an answer so I can give you credit. – Thom Oct 04 '19 at 15:09

1 Answers1

2

If your method does some async work then you should have your test in a different way, like for example using fakeAsync and tick() to stub the async.

If you update your question with the method code I can give you more detailed answer.

Ismail
  • 2,778
  • 2
  • 24
  • 39