Use Jasmine Matchers

Learn to fuzzy match objects, strings, sets, and arrays with Jasmine's matchers. Instruct Jasmine to focus on a single test and only run and report it.

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' and typeof String('my string') === 'string' are both true. But typeof new String('my string') === 'object'. Note that the use of new keyword creates an object.

Below is a unit testing example.

Get hands-on with 1400+ tech skills courses.