Home > front end >  How do you deal with a fluctuating unit test case with Jasmine?
How do you deal with a fluctuating unit test case with Jasmine?

Time:11-07

I am writing unit test cases using Jasmine for Angular 13 project. there is a test case which passes sometimes and fails sometimes. I presume this happens because of order of the tests execution. Any idea how to deal with it?

An error was thrown in afterall

CodePudding user response:

By default the tests run in a random order each time. There is a seed value so that you can recreate the order. You can read on how to approach that in this answer.

Once you have yours executing where it fails each time you will easily know if any of the following has actually fixed your issue.

You can also check for anywhere you are subscribing to something - every time you subscribe in your test you need to make sure that it gets unsubscribed at the end of the test. To do this you can put .pipe(take(1)) or capture the subscription object and call unsubscribe on it.

const sub = someService.callObservable().subscribe();
// verify what you need to

sub.unsubscribe();

A third concept to look at - any variables you have defined above the beforeEach should be set to a new value in the beforeEach. Otherwise you will have the same objects reused between tests and that can lead to issues.

  • Related