Custom Matchers
Discover how to write custom matchers in Jasmine to simplify repetitive test expectations and enhance code clarity. This lesson guides you through defining matcher objects, integrating them within test suites, and handling both positive and negative cases, using examples like toBeEven and toBeMonday to improve your Angular testing skills.
We'll cover the following...
Jasmine gives us the ability to write our own custom matchers. This allows us to clean up our code, where we keep having to repeat the same expectations. To add a custom matcher, we must do the following two things:
-
Define an object that specifies the behavior of the custom matcher.
-
In the
beforeEachblock of our test suite, we use theaddMatchersmethod to extend the Jasmine functionality with our custom matcher.
Code example
Suppose we want to test a function that must always return even numbers. We could use the snippet result % 2 == 0 to check that the ...