Jasmine - any boolean (jasmine.any(Boolean))

Problem

I write unit tests for angular using karma, jasmine. Try to write:

expect(item).toEqual(jasmine.any(Boolean));

but got:

Expected true to equal <jasmine.any(function Boolean() { [native code] })>.

mm.. maybe i do something wrong) or is it another way to write test for value in that case:

if (true or false) - passed, if any other - fail

Problem courtesy of: Vladimir Gordienko

Solution

I think what you need is a custom Matcher something like this:

toBeBoolean : function () {
  return {
    compare : function (actual, expected) {
      return {
        pass : (typeof actual === 'boolean'),
        message : 'Expected ' + actual + ' is not boolean'
      };
    }
  };
}

How to create a Custom Matcher

Solution courtesy of: Dalorzo

Discussion

For me, the marked solution isn't correct. At least not for the way I expect it to be used. I did it like this:

jasmine.addMatchers({
    toBeBoolean: function () {
        return {
            compare: function (actual, expected) {
                return {
                    pass: typeof actual === 'boolean',
                    message: 'Expected ' + actual + ' is not boolean'
                };
            }
        };
    }
});

because you are not passing an expected value, just the actual. So the way you would invoke this is:

expect(true|false).toBeBoolean();
Discussion courtesy of: r3plica

I would expect your code work as expected but obviously it seems like jasmine behaves a little weird in this case.

I would recommend you the following workaround:

expect(typeof item).toEqual('boolean');

Discussion courtesy of: Markus Peröbner

Also possible with:

expect(item).toMatch(/true|false/);
Discussion courtesy of: Julius

This recipe can be found in it's original form on Stack Over Flow.