Skip to content
Advertisement

Unit test a method called from a method

I have an angular application and a method that gets provoked on click. In this method I am passing a value to another private method.

.ts file

JavaScript

.spec file

JavaScript

How do I test the line const ids = [item.data['id']]; and check the call of this.anotherMethod(ids);

Advertisement

Answer

There is a good practice for it: check the expected results and avoid checking which method is being called in between. It would make the test easy to maintain.

Let’s explore it with an example.

JavaScript

What are the options to test it? I see two:

Bad one

Spy on the anotherMethod:

JavaScript

Good one

Test the expected results:

JavaScript

Why is the good one better? Consider you refactored the onViewItem method. Now it looks like this:

JavaScript

The arguments are the same. Results yielded by the method execution exactly the same as well. if you had a spy on the function you are forced to refactor the test. If you just tested the expected results – you are good to go.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement