Use Jasmine Matchers
Explore how to apply Jasmine matchers to verify JavaScript functions that produce random outputs and complex structures. Understand matchers such as jasmine.any, stringMatching, objectContaining, arrayContaining, and setContaining to write flexible, reliable unit tests that accommodate variability in output types or values.
Random output function
For functions with the random output, unit testing becomes a little bit harder. For example:
function random() {
return Math.random() > 0.5 ? 'a string' : 'another string';
}
// Unit test
it('should verify function returns a random string', () => {
expect(random()).toEqual('a string');
});
The above test fails 50% of the time as the random function gets a Math.random value that is anywhere between 0 and 1. Based on that, it decides which of the two strings to return.
This is where the matcher jasmine.any comes in. It allows toEqual to verify that the expected is an instance of the constructor function that is passed in jasmine.any. In the example above:
// Unit test
it('should verify function returns a random string', () => {
expect(random()).toEqual(jasmine.any(String));
});
That is to say, “Hey, Jasmine, make sure that the expected is of the type String, or fail the test.”
Notice the uppercase
String. That’s the runtime available function object String. So, typeof 'my string' === 'string'andtypeof String('my string') === 'string'are bothtrue. ...