Karma and Jasmine are one of the most popular combinations which help developers to test front-end code. To run the same test with different data input (data-driven testing)
we can use a loop with it inside, or we can import one of the available library, but today I’ll show you how to make that smartly by own hands.
All examples here are in default Angular language - typescript.
Our goals:
We would like to run a single test with many input cases
We should be able to see excellent visual results
Test invocation should consist with Jasmine flow
The first shot
The example of usage:
Okay, what we’ve got here? We’ve created the using function which takes values array as an argument, and it provides multiple input cases.
We are able now to run a single test with different parameters - it’s nice but it still has some place for improvements.
The first proposition is to add an option to make each parametrized test visible in test results. We can add some argument which tells function if test cases should be wrapped or unwrapped. Let’s go for that.
Now if we going to run following test:
We’ve got pretty good visual result:
Excellent, a little summary:
we can run single test logic for multiple input values
we can run multiple cases as a singular test, and we can run separate test per case too
Please notice that we’ve missed default done() parameter in it function but there is no sense to run it inside each execution. If we need to process some async flow we can, for example, add done() inside using function after whole flow.
Okay so we’ve got something it would work but… I feel like this using function may be better, and there is one significant disadvantage: we are not able to put multiple test case parameters per test invocation.
More improvements
The perfect situation is if we’ll able to put differently named parameters, so our test invocation may look like that:
How can we achieve something like that? the way to go is the following:
Now our results look much better :)
The final refactoring
Would you like to have the function more similar to it function? - I have something for you. We can move our input at the end of invocation. We need to do some lazy-execution stuff to achieve that. Let’s try
Summary
Uff, finally we’ve finished :) The end of this post is an excellent place to put examples of our final its function.