I am very new to Jasmine and have come across a situation where I expect either String or null. I tried to do either inside toEqual, but I see some odd results that make me believe that I am doing it wrong. What is the best way to make this happen?
Maybe I'm just wrong in my testing. Should I just abandon this idea to conduct one test to test both situations?
describe("Jasmine", function () { //1 it("should be able to handle any(String) || null within toEqual for string", function () { expect("aString").toEqual(jasmine.any(String) || null); }); //2 it("should be able to handle any(String) || null within toEqual for null", function () { expect(null).toEqual(jasmine.any(String) || null); }); //3 it("should be able to handle null || any(String) within toEqual for string", function () { expect("aString").toEqual(null || jasmine.any(String)); }); //4 it("should be able to handle null || any(String) within toEqual for null", function () { expect(null).toEqual(null || jasmine.any(String)); }); });
- Pass
Expected null to equal <jasmine.any(function String() { [native code] })>.- Pass
Expected null to equal <jasmine.any(function String() { [native code] })>.
I understand that there is also toBeNull (), which is probably the reason that the results are so dubious, but without the βorβ chain, I did not know how to turn it on.
(Running Jasmine 1.3.1, revision 1354556913)
Solved! The complete solution is below if anyone is interested.
describe("Jasmine", function () { beforeEach(function () { this.addMatchers({ toBeStringOrNull: function () { var actual = this.actual; this.message = function () { return "Expected " + actual + " to be either string or null"; }; return typeof actual === 'string' || actual instanceof String || actual === null; } }); });
source share