Best JavaScript code snippet using sinon
create-matcher.test.js
Source:create-matcher.test.js
...65}66describe("matcher", function () {67 it("returns matcher", function () {68 // eslint-disable-next-line no-empty-function69 var match = createMatcher(function () {});70 assert(createMatcher.isMatcher(match));71 });72 it("throws for non-string message arguments", function () {73 var iAmNotAString = {};74 assert.exception(function () {75 // eslint-disable-next-line no-empty-function76 createMatcher(function () {}, iAmNotAString);77 });78 });79 it("throws for superfluous arguments", function () {80 assert.exception(function () {81 // eslint-disable-next-line no-empty-function82 createMatcher(function () {}, "error msg", "needless argument");83 });84 });85 it("exposes test function", function () {86 // eslint-disable-next-line no-empty-function87 var test = function () {};88 var match = createMatcher(test);89 assert.same(match.test, test);90 });91 it("returns true if properties are equal", function () {92 var match = createMatcher({ str: "sinon", nr: 1 });93 assert(match.test({ str: "sinon", nr: 1, other: "ignored" }));94 });95 it("returns true if properties are deep equal", function () {96 var match = createMatcher({ deep: { str: "sinon" } });97 assert(match.test({ deep: { str: "sinon", ignored: "value" } }));98 });99 it("returns false if a property is not equal", function () {100 var match = createMatcher({ str: "sinon", nr: 1 });101 assert.isFalse(match.test({ str: "sinon", nr: 2 }));102 });103 it("returns false if a property is missing", function () {104 var match = createMatcher({ str: "sinon", nr: 1 });105 assert.isFalse(match.test({ nr: 1 }));106 });107 it("returns true if array is equal", function () {108 var match = createMatcher({ arr: ["a", "b"] });109 assert(match.test({ arr: ["a", "b"] }));110 });111 it("returns false if array is not equal", function () {112 var match = createMatcher({ arr: ["b", "a"] });113 assert.isFalse(match.test({ arr: ["a", "b"] }));114 });115 it("returns false if array is not equal (even if the contents would match (deep equal))", function () {116 var match = createMatcher([{ str: "sinon" }]);117 assert.isFalse(match.test([{ str: "sinon", ignored: "value" }]));118 });119 it("returns true if set iterator is equal", function () {120 var match = createMatcher(new Set(["a", "b"]).values());121 assert(match.test(new Set(["a", "b"]).values()));122 });123 it("returns false if set iterator is not equal", function () {124 var match = createMatcher(new Set(["a", "b"]).values());125 assert.isFalse(match.test(new Set(["a", "b", "c"]).values()));126 });127 it("returns true if map iterator is equal", function () {128 var map = new Map();129 map.set("a", 1);130 map.set("b", 2);131 var match = createMatcher(map.values());132 assert(match.test(map.values()));133 });134 it("returns false if map iterator is not equal", function () {135 var map = new Map();136 map.set("a", 1);137 map.set("b", 2);138 var wrongMap = new Map();139 wrongMap.set("a", 1);140 wrongMap.set("b", 2);141 wrongMap.set("c", 3);142 var match = createMatcher(map.values());143 assert.isFalse(match.test(wrongMap.values()));144 });145 it("returns true if number objects are equal", function () {146 /*eslint-disable no-new-wrappers*/147 var match = createMatcher({ one: new Number(1) });148 assert(match.test({ one: new Number(1) }));149 /*eslint-enable no-new-wrappers*/150 });151 it("returns true if test matches", function () {152 var match = createMatcher({ prop: createMatcher.typeOf("boolean") });153 assert(match.test({ prop: true }));154 });155 it("returns false if test does not match", function () {156 var match = createMatcher({ prop: createMatcher.typeOf("boolean") });157 assert.isFalse(match.test({ prop: "no" }));158 });159 it("returns true if deep test matches", function () {160 var match = createMatcher({161 deep: { prop: createMatcher.typeOf("boolean") },162 });163 assert(match.test({ deep: { prop: true } }));164 });165 it("returns false if deep test does not match", function () {166 var match = createMatcher({167 deep: { prop: createMatcher.typeOf("boolean") },168 });169 assert.isFalse(match.test({ deep: { prop: "no" } }));170 });171 it("returns false if tested value is null or undefined", function () {172 var match = createMatcher({});173 assert.isFalse(match.test(null));174 assert.isFalse(match.test(undefined));175 });176 it("returns true if error message matches", function () {177 var match = createMatcher({ message: "evil error" });178 assert(match.test(new Error("evil error")));179 });180 it("returns true if string property matches", function () {181 var match = createMatcher({ length: 5 });182 assert(match.test("sinon"));183 });184 it("returns true if number property matches", function () {185 var match = createMatcher({ toFixed: createMatcher.func });186 assert(match.test(0));187 });188 it("returns true for string match", function () {189 var match = createMatcher("sinon");190 assert(match.test("sinon"));191 });192 it("returns true for substring match", function () {193 var match = createMatcher("no");194 assert(match.test("sinon"));195 });196 it("returns false for string mismatch", function () {197 var match = createMatcher("Sinon.JS");198 assert.isFalse(match.test(null));199 assert.isFalse(match.test({}));200 assert.isFalse(match.test("sinon"));201 assert.isFalse(match.test("sinon.js"));202 });203 it("returns true for regexp match", function () {204 var match = createMatcher(/^[sino]+$/);205 assert(match.test("sinon"));206 });207 it("returns false for regexp string mismatch", function () {208 var match = createMatcher(/^[sin]+$/);209 assert.isFalse(match.test("sinon"));210 });211 it("returns false for regexp type mismatch", function () {212 var match = createMatcher(/.*/);213 assert.isFalse(match.test());214 assert.isFalse(match.test(null));215 assert.isFalse(match.test(123));216 assert.isFalse(match.test({}));217 });218 it("returns true for number match", function () {219 var match = createMatcher(1);220 assert(match.test(1));221 assert(match.test("1"));222 assert(match.test(true));223 });224 it("returns false for number mismatch", function () {225 var match = createMatcher(1);226 assert.isFalse(match.test());227 assert.isFalse(match.test(null));228 assert.isFalse(match.test(2));229 assert.isFalse(match.test(false));230 assert.isFalse(match.test({}));231 });232 it("returns true for Symbol match", function () {233 if (typeof Symbol === "function") {234 var symbol = Symbol("a symbol");235 var match = createMatcher(symbol);236 assert(match.test(symbol));237 }238 });239 it("returns false for Symbol mismatch", function () {240 if (typeof Symbol === "function") {241 var match = createMatcher(Symbol("a symbol"));242 assert.isFalse(match.test());243 assert.isFalse(match.test(Symbol(null)));244 assert.isFalse(match.test(Symbol("another symbol")));245 assert.isFalse(match.test(Symbol({})));246 }247 });248 it("returns true for Symbol inside object", function () {249 if (typeof Symbol === "function") {250 var symbol = Symbol("a symbol");251 var match = createMatcher({ prop: symbol });252 assert(match.test({ prop: symbol }));253 }254 });255 it("returns true for Symbol key", function () {256 if (typeof Symbol === "function") {257 var symbol = Symbol("a symbol");258 var actual = { quux: "baz" };259 var expected = {};260 actual[symbol] = "foo";261 expected[symbol] = "foo";262 var match = createMatcher(expected);263 assert(match.test(actual));264 }265 });266 it("returns false for Symbol key mismatch", function () {267 if (typeof Symbol === "function") {268 var symbol = Symbol("a symbol");269 var actual = {};270 var expected = {};271 actual[symbol] = "foo";272 expected[symbol] = "bar";273 var match = createMatcher(expected);274 assert.isFalse(match.test(actual));275 }276 });277 it("returns true if test function in object returns true", function () {278 var match = createMatcher({279 test: function () {280 return true;281 },282 });283 assert(match.test());284 });285 it("returns false if test function in object returns false", function () {286 var match = createMatcher({287 test: function () {288 return false;289 },290 });291 assert.isFalse(match.test());292 });293 it("returns false if test function in object returns nothing", function () {294 // eslint-disable-next-line no-empty-function295 var match = createMatcher({ test: function () {} });296 assert.isFalse(match.test());297 });298 it("passes actual value to test function in object", function () {299 var match = createMatcher({300 test: function (arg) {301 return arg;302 },303 });304 assert(match.test(true));305 });306 it("uses matcher", function () {307 var match = createMatcher(createMatcher("test"));308 assert(match.test("testing"));309 });310 describe(".toString", function () {311 it("returns message", function () {312 var message = "hello sinonMatch";313 // eslint-disable-next-line no-empty-function314 var match = createMatcher(function () {}, message);315 assert.same(match.toString(), message);316 });317 it("defaults to match(functionName)", function () {318 // eslint-disable-next-line no-empty-function319 var match = createMatcher(function custom() {});320 assert.same(match.toString(), "match(custom)");321 });322 });323 describe(".any", function () {324 it("is matcher", function () {325 assert(createMatcher.isMatcher(createMatcher.any));326 });327 it("returns true when tested", function () {328 assert(createMatcher.any.test());329 });330 });331 describe(".defined", function () {332 it("is matcher", function () {333 assert(createMatcher.isMatcher(createMatcher.defined));334 });335 it("returns false if test is called with null", function () {336 assert.isFalse(createMatcher.defined.test(null));337 });338 it("returns false if test is called with undefined", function () {339 assert.isFalse(createMatcher.defined.test(undefined));340 });341 it("returns true if test is called with any value", function () {342 assert(createMatcher.defined.test(false));343 assert(createMatcher.defined.test(true));344 assert(createMatcher.defined.test(0));345 assert(createMatcher.defined.test(1));346 assert(createMatcher.defined.test(""));347 });348 it("returns true if test is called with any object", function () {349 assert(createMatcher.defined.test({}));350 // eslint-disable-next-line no-empty-function351 assert(createMatcher.defined.test(function () {}));352 });353 });354 describe(".truthy", function () {355 it("is matcher", function () {356 assert(createMatcher.isMatcher(createMatcher.truthy));357 });358 it("returns true if test is called with trueish value", function () {359 assert(createMatcher.truthy.test(true));360 assert(createMatcher.truthy.test(1));361 assert(createMatcher.truthy.test("yes"));362 });363 it("returns false if test is called falsy value", function () {364 assert.isFalse(createMatcher.truthy.test(false));365 assert.isFalse(createMatcher.truthy.test(null));366 assert.isFalse(createMatcher.truthy.test(undefined));367 assert.isFalse(createMatcher.truthy.test(""));368 });369 });370 describe(".falsy", function () {371 it("is matcher", function () {372 assert(createMatcher.isMatcher(createMatcher.falsy));373 });374 it("returns true if test is called falsy value", function () {375 assert(createMatcher.falsy.test(false));376 assert(createMatcher.falsy.test(null));377 assert(createMatcher.falsy.test(undefined));378 assert(createMatcher.falsy.test(""));379 });380 it("returns false if test is called with trueish value", function () {381 assert.isFalse(createMatcher.falsy.test(true));382 assert.isFalse(createMatcher.falsy.test(1));383 assert.isFalse(createMatcher.falsy.test("yes"));384 });385 });386 describe(".same", function () {387 it("returns matcher", function () {388 var same = createMatcher.same();389 assert(createMatcher.isMatcher(same));390 });391 it("returns true if test is called with same argument", function () {392 var object = {};393 var same = createMatcher.same(object);394 assert(same.test(object));395 });396 it("returns true if test is called with same symbol", function () {397 if (typeof Symbol === "function") {398 var symbol = Symbol("a symbol");399 var same = createMatcher.same(symbol);400 assert(same.test(symbol));401 }402 });403 it("returns false if test is not called with same argument", function () {404 var same = createMatcher.same({});405 assert.isFalse(same.test({}));406 });407 });408 describe(".in", function () {409 it("returns matcher", function () {410 var inMatcher = createMatcher.in([]);411 assert(createMatcher.isMatcher(inMatcher));412 });413 it("throws if given argument is not an array", function () {414 var arg = "not-array";415 assert.exception(416 function () {417 createMatcher.in(arg);418 },419 { name: "TypeError", message: "array expected" }420 );421 });422 describe("when given argument is an array", function () {423 var arrays = [424 [1, 2, 3],425 ["a", "b", "c"],426 [{ a: "a" }, { b: "b" }],427 // eslint-disable-next-line no-empty-function428 [function () {}, function () {}],429 [null, undefined],430 ];431 it("returns true if the tested value in the given array", function () {432 arrays.forEach(function (array) {433 var inMatcher = createMatcher.in(array);434 assert.isTrue(inMatcher.test(array[0]));435 });436 });437 it("returns false if the tested value not in the given array", function () {438 arrays.forEach(function (array) {439 var inMatcher = createMatcher.in(array);440 assert.isFalse(inMatcher.test("something else"));441 });442 });443 });444 });445 describe(".typeOf", function () {446 it("throws if given argument is not a string", function () {447 assert.exception(448 function () {449 createMatcher.typeOf();450 },451 { name: "TypeError" }452 );453 assert.exception(454 function () {455 createMatcher.typeOf(123);456 },457 { name: "TypeError" }458 );459 });460 it("returns matcher", function () {461 var typeOf = createMatcher.typeOf("string");462 assert(createMatcher.isMatcher(typeOf));463 });464 it("returns true if test is called with string", function () {465 var typeOf = createMatcher.typeOf("string");466 assert(typeOf.test("Sinon.JS"));467 });468 it("returns false if test is not called with string", function () {469 var typeOf = createMatcher.typeOf("string");470 assert.isFalse(typeOf.test(123));471 });472 it("returns true if test is called with symbol", function () {473 if (typeof Symbol === "function") {474 var typeOf = createMatcher.typeOf("symbol");475 assert(typeOf.test(Symbol("a symbol")));476 }477 });478 it("returns true if test is called with regexp", function () {479 var typeOf = createMatcher.typeOf("regexp");480 assert(typeOf.test(/.+/));481 });482 it("returns false if test is not called with regexp", function () {483 var typeOf = createMatcher.typeOf("regexp");484 assert.isFalse(typeOf.test(true));485 });486 });487 describe(".instanceOf", function () {488 it("throws if given argument is not a function", function () {489 assert.exception(490 function () {491 createMatcher.instanceOf();492 },493 { name: "TypeError" }494 );495 assert.exception(496 function () {497 createMatcher.instanceOf("foo");498 },499 { name: "TypeError" }500 );501 });502 if (503 typeof Symbol !== "undefined" &&504 // eslint-disable-next-line mocha/no-setup-in-describe505 typeof Symbol.hasInstance !== "undefined"506 ) {507 it("does not throw if given argument defines Symbol.hasInstance", function () {508 var objectWithCustomTypeChecks = {};509 // eslint-disable-next-line no-empty-function510 objectWithCustomTypeChecks[Symbol.hasInstance] = function () {};511 createMatcher.instanceOf(objectWithCustomTypeChecks);512 });513 }514 it("returns matcher", function () {515 // eslint-disable-next-line no-empty-function516 var instanceOf = createMatcher.instanceOf(function () {});517 assert(createMatcher.isMatcher(instanceOf));518 });519 it("returns true if test is called with instance of argument", function () {520 var instanceOf = createMatcher.instanceOf(Array);521 assert(instanceOf.test([]));522 });523 it("returns false if test is not called with instance of argument", function () {524 var instanceOf = createMatcher.instanceOf(Array);525 assert.isFalse(instanceOf.test({}));526 });527 describe("when Symbol is not defined", function () {528 it("should call assertType and return a matcher", function () {529 var createMatcherStub = proxyquire("./create-matcher", {530 "@sinonjs/commons": {531 typeOf: function () {532 return "undefined";533 },534 },535 // eslint-disable-next-line no-empty-function536 "./create-matcher/assert-type": function () {},537 });538 // eslint-disable-next-line no-empty-function539 var instanceOf = createMatcherStub.instanceOf(function () {});540 assert.isTrue(createMatcherStub.isMatcher(instanceOf));541 });542 });543 });544 // eslint-disable-next-line mocha/no-setup-in-describe545 describe(".has", propertyMatcherTests(createMatcher.has));546 // eslint-disable-next-line mocha/no-setup-in-describe547 describe(".hasOwn", propertyMatcherTests(createMatcher.hasOwn));548 describe(549 ".hasNested",550 // eslint-disable-next-line mocha/no-setup-in-describe551 propertyMatcherTests(createMatcher.hasNested, function () {552 it("compares nested value", function () {553 var hasNested = createMatcher.hasNested("foo.bar", "doo");554 assert(hasNested.test({ foo: { bar: "doo" } }));555 });556 it("compares nested array value", function () {557 var hasNested = createMatcher.hasNested("foo[0].bar", "doo");558 assert(hasNested.test({ foo: [{ bar: "doo" }] }));559 });560 })561 );562 describe(".json", function () {563 it("throws if argument cannot be the result of JSON.parse", function () {564 assert.exception(565 function () {566 createMatcher.json();567 },568 { name: "TypeError" }569 );570 assert.exception(571 function () {572 // eslint-disable-next-line no-empty-function573 createMatcher.json(function () {});574 },575 { name: "TypeError" }576 );577 if (typeof Symbol !== "undefined") {578 assert.exception(579 function () {580 createMatcher.json(Symbol("a symbol"));581 },582 { name: "TypeError" }583 );584 }585 });586 it("returns matcher", function () {587 var json = createMatcher.json({});588 assert(createMatcher.isMatcher(json));589 });590 it("returns false if actual cannot be parsed", function () {591 var json = createMatcher.json(null);592 var result;593 refute.exception(function () {594 result = json.test("not json");595 });596 assert.isFalse(result);597 });598 it("returns true for null match", function () {599 assert(createMatcher.json(null).test("null"));600 });601 it("returns false for null mismatch", function () {602 assert.isFalse(createMatcher.json(null).test("false"));603 assert.isFalse(createMatcher.json(null).test('""'));604 });605 it("returns true for boolean match", function () {606 assert(createMatcher.json(true).test("true"));607 assert(createMatcher.json(false).test("false"));608 });609 it("returns false for boolean mismatch", function () {610 assert.isFalse(createMatcher.json(false).test("true"));611 assert.isFalse(createMatcher.json(true).test("false"));612 assert.isFalse(createMatcher.json(true).test("1"));613 assert.isFalse(createMatcher.json(false).test("null"));614 });615 it("returns true for number match", function () {616 assert(createMatcher.json(0).test("0"));617 assert(createMatcher.json(1).test("1"));618 });619 it("returns false for number mismatch", function () {620 assert.isFalse(createMatcher.json(0).test("1"));621 assert.isFalse(createMatcher.json(1).test("0"));622 assert.isFalse(createMatcher.json(0).test("null"));623 assert.isFalse(createMatcher.json(0).test("false"));624 });625 it("returns true for string match", function () {626 assert(createMatcher.json("").test('""'));627 assert(createMatcher.json("test").test('"test"'));628 });629 it("returns false for string mismatch", function () {630 assert.isFalse(createMatcher.json("").test('"test"'));631 assert.isFalse(createMatcher.json("test").test('"tes"'));632 assert.isFalse(createMatcher.json("1").test("1"));633 assert.isFalse(createMatcher.json("true").test("true"));634 });635 it("returns true for object match", function () {636 assert(createMatcher.json({}).test("{}"));637 assert(638 createMatcher639 .json({ foo: 1, bar: "yes" })640 .test(JSON.stringify({ bar: "yes", foo: 1 }))641 );642 });643 it("returns false for object mismatch", function () {644 assert.isFalse(createMatcher.json({ foo: 1 }).test("{}"));645 assert.isFalse(646 createMatcher.json({}).test(JSON.stringify({ foo: 1 }))647 );648 });649 it("returns true for array match", function () {650 assert(createMatcher.json([]).test("[]"));651 assert(652 createMatcher.json([1, "yes"]).test(JSON.stringify([1, "yes"]))653 );654 });655 it("returns false for array mismatch", function () {656 assert.isFalse(createMatcher.json([1]).test("[]"));657 assert.isFalse(createMatcher.json([]).test("[1]"));658 assert.isFalse(createMatcher.json([1, 2]).test("[2, 1]"));659 });660 it('wraps the given value with "json()"', function () {661 assert.equals(createMatcher.json(null).toString(), "json(null)");662 assert.equals(663 createMatcher.json({ foo: "bar" }).toString(),664 'json({\n "foo": "bar"\n})'665 );666 });667 });668 describe(".hasSpecial", function () {669 it("returns true if object has inherited property", function () {670 var has = createMatcher.has("toString");671 assert(has.test({}));672 });673 it("only includes property in message", function () {674 var has = createMatcher.has("test");675 assert.equals(has.toString(), 'has("test")');676 });677 it("includes property and value in message", function () {678 var has = createMatcher.has("test", undefined);679 assert.equals(has.toString(), 'has("test", undefined)');680 });681 it("returns true if string function matches", function () {682 var has = createMatcher.has("toUpperCase", createMatcher.func);683 assert(has.test("sinon"));684 });685 it("returns true if number function matches", function () {686 var has = createMatcher.has("toFixed", createMatcher.func);687 assert(has.test(0));688 });689 it("returns true if object has Symbol", function () {690 if (typeof Symbol === "function") {691 var symbol = Symbol("a symbol");692 var has = createMatcher.has("prop", symbol);693 assert(has.test({ prop: symbol }));694 }695 });696 it("returns true if embedded object has Symbol", function () {697 if (typeof Symbol === "function") {698 var symbol = Symbol("a symbol");699 var has = createMatcher.has(700 "prop",701 createMatcher.has("embedded", symbol)702 );703 assert(has.test({ prop: { embedded: symbol }, ignored: 42 }));704 }705 });706 });707 describe(".hasOwnSpecial", function () {708 it("returns false if object has inherited property", function () {709 var hasOwn = createMatcher.hasOwn("toString");710 assert.isFalse(hasOwn.test({}));711 });712 it("only includes property in message", function () {713 var hasOwn = createMatcher.hasOwn("test");714 assert.equals(hasOwn.toString(), 'hasOwn("test")');715 });716 it("includes property and value in message", function () {717 var hasOwn = createMatcher.hasOwn("test", undefined);718 assert.equals(hasOwn.toString(), 'hasOwn("test", undefined)');719 });720 });721 describe(".every", function () {722 it("throws if given argument is not a matcher", function () {723 assert.exception(724 function () {725 createMatcher.every({});726 },727 { name: "TypeError" }728 );729 assert.exception(730 function () {731 createMatcher.every(123);732 },733 { name: "TypeError" }734 );735 assert.exception(736 function () {737 createMatcher.every("123");738 },739 { name: "TypeError" }740 );741 });742 it("returns matcher", function () {743 var every = createMatcher.every(createMatcher.any);744 assert(createMatcher.isMatcher(every));745 });746 it('wraps the given matcher message with an "every()"', function () {747 var every = createMatcher.every(createMatcher.number);748 assert.equals(every.toString(), 'every(typeOf("number"))');749 });750 it("fails to match anything that is not an object or an iterable", function () {751 var every = createMatcher.every(createMatcher.any);752 refute(every.test(1));753 refute(every.test("a"));754 refute(every.test(null));755 // eslint-disable-next-line no-empty-function756 refute(every.test(function () {}));757 });758 it("matches an object if the predicate is true for every property", function () {759 var every = createMatcher.every(createMatcher.number);760 assert(every.test({ a: 1, b: 2 }));761 });762 it("fails if the predicate is false for some of the object properties", function () {763 var every = createMatcher.every(createMatcher.number);764 refute(every.test({ a: 1, b: "b" }));765 });766 it("matches an array if the predicate is true for every element", function () {767 var every = createMatcher.every(createMatcher.number);768 assert(every.test([1, 2]));769 });770 it("fails if the predicate is false for some of the array elements", function () {771 var every = createMatcher.every(createMatcher.number);772 refute(every.test([1, "b"]));773 });774 if (typeof Set === "function") {775 it("matches an iterable if the predicate is true for every element", function () {776 var every = createMatcher.every(createMatcher.number);777 var set = new Set();778 set.add(1);779 set.add(2);780 assert(every.test(set));781 });782 it("fails if the predicate is false for some of the iterable elements", function () {783 var every = createMatcher.every(createMatcher.number);784 var set = new Set();785 set.add(1);786 set.add("b");787 refute(every.test(set));788 });789 }790 });791 describe(".some", function () {792 it("throws if given argument is not a matcher", function () {793 assert.exception(794 function () {795 createMatcher.some({});796 },797 { name: "TypeError" }798 );799 assert.exception(800 function () {801 createMatcher.some(123);802 },803 { name: "TypeError" }804 );805 assert.exception(806 function () {807 createMatcher.some("123");808 },809 { name: "TypeError" }810 );811 });812 it("returns matcher", function () {813 var some = createMatcher.some(createMatcher.any);814 assert(createMatcher.isMatcher(some));815 });816 it('wraps the given matcher message with an "some()"', function () {817 var some = createMatcher.some(createMatcher.number);818 assert.equals(some.toString(), 'some(typeOf("number"))');819 });820 it("fails to match anything that is not an object or an iterable", function () {821 var some = createMatcher.some(createMatcher.any);822 refute(some.test(1));823 refute(some.test("a"));824 refute(some.test(null));825 // eslint-disable-next-line no-empty-function826 refute(some.test(function () {}));827 });828 it("matches an object if the predicate is true for some of the properties", function () {829 var some = createMatcher.some(createMatcher.number);830 assert(some.test({ a: 1, b: "b" }));831 });832 it("fails if the predicate is false for all of the object properties", function () {833 var some = createMatcher.some(createMatcher.number);834 refute(some.test({ a: "a", b: "b" }));835 });836 it("matches an array if the predicate is true for some element", function () {837 var some = createMatcher.some(createMatcher.number);838 assert(some.test([1, "b"]));839 });840 it("fails if the predicate is false for all of the array elements", function () {841 var some = createMatcher.some(createMatcher.number);842 refute(some.test(["a", "b"]));843 });844 if (typeof Set === "function") {845 it("matches an iterable if the predicate is true for some element", function () {846 var some = createMatcher.some(createMatcher.number);847 var set = new Set();848 set.add(1);849 set.add("b");850 assert(some.test(set));851 });852 it("fails if the predicate is false for all of the iterable elements", function () {853 var some = createMatcher.some(createMatcher.number);854 var set = new Set();855 set.add("a");856 set.add("b");857 refute(some.test(set));858 });859 }860 });861 describe(".bool", function () {862 it("is typeOf boolean matcher", function () {863 var bool = createMatcher.bool;864 assert(createMatcher.isMatcher(bool));865 assert.equals(bool.toString(), 'typeOf("boolean")');866 });867 });868 describe(".number", function () {869 it("is typeOf number matcher", function () {870 var number = createMatcher.number;871 assert(createMatcher.isMatcher(number));872 assert.equals(number.toString(), 'typeOf("number")');873 });874 });875 describe(".string", function () {876 it("is typeOf string matcher", function () {877 var string = createMatcher.string;878 assert(createMatcher.isMatcher(string));879 assert.equals(string.toString(), 'typeOf("string")');880 });881 });882 describe(".object", function () {883 it("is typeOf object matcher", function () {884 var object = createMatcher.object;885 assert(createMatcher.isMatcher(object));886 assert.equals(object.toString(), 'typeOf("object")');887 });888 });889 describe(".func", function () {890 it("is typeOf function matcher", function () {891 var func = createMatcher.func;892 assert(createMatcher.isMatcher(func));893 assert.equals(func.toString(), 'typeOf("function")');894 });895 });896 describe(".array", function () {897 it("is typeOf array matcher", function () {898 var array = createMatcher.array;899 assert(createMatcher.isMatcher(array));900 assert.equals(array.toString(), 'typeOf("array")');901 });902 describe("array.deepEquals", function () {903 it("has a .deepEquals matcher", function () {904 var deepEquals = createMatcher.array.deepEquals([1, 2, 3]);905 assert(createMatcher.isMatcher(deepEquals));906 assert.equals(deepEquals.toString(), "deepEquals([1,2,3])");907 });908 describe("one-dimensional arrays", function () {909 it("matches arrays with the exact same elements", function () {910 var deepEquals = createMatcher.array.deepEquals([1, 2, 3]);911 assert(deepEquals.test([1, 2, 3]));912 assert.isFalse(deepEquals.test([1, 2]));913 assert.isFalse(deepEquals.test([3]));914 });915 });916 describe("nested arrays", function () {917 var deepEquals;918 beforeEach(function () {919 deepEquals = createMatcher.array.deepEquals([920 ["test"],921 ["nested"],922 ["arrays"],923 [{ with: "object" }],924 ]);925 });926 it("matches nested arrays with the exact same elements", function () {927 assert(928 deepEquals.test([929 ["test"],930 ["nested"],931 ["arrays"],932 [{ with: "object" }],933 ])934 );935 });936 it("fails when nested arrays are not in the same order", function () {937 assert.isFalse(938 deepEquals.test([939 ["test"],940 ["arrays"],941 ["nested"],942 [{ with: "object" }],943 ])944 );945 });946 it("fails when nested arrays don't have same count", function () {947 assert.isFalse(deepEquals.test([["test"], ["arrays"]]));948 });949 it("matches nested, empty arrays", function () {950 var empty = createMatcher.array.deepEquals([[], []]);951 assert.isTrue(empty.test([[], []]));952 });953 });954 it("fails when passed a non-array object", function () {955 var deepEquals = createMatcher.array.deepEquals([956 "one",957 "two",958 "three",959 ]);960 assert.isFalse(961 deepEquals.test({962 0: "one",963 1: "two",964 2: "three",965 length: 3,966 })967 );968 });969 });970 describe("array.startsWith", function () {971 it("has a .startsWith matcher", function () {972 var startsWith = createMatcher.array.startsWith([1, 2]);973 assert(createMatcher.isMatcher(startsWith));974 assert.equals(startsWith.toString(), "startsWith([1,2])");975 });976 it("matches arrays starting with the same elements", function () {977 assert(createMatcher.array.startsWith([1]).test([1, 2]));978 assert(createMatcher.array.startsWith([1, 2]).test([1, 2]));979 assert.isFalse(980 createMatcher.array.startsWith([1, 2, 3]).test([1, 2])981 );982 assert.isFalse(983 createMatcher.array.startsWith([2]).test([1, 2])984 );985 });986 it("fails when passed a non-array object", function () {987 var startsWith = createMatcher.array.startsWith(["one", "two"]);988 assert.isFalse(989 startsWith.test({990 0: "one",991 1: "two",992 2: "three",993 length: 3,994 })995 );996 });997 });998 describe("array.endsWith", function () {999 it("has an .endsWith matcher", function () {1000 var endsWith = createMatcher.array.endsWith([2, 3]);1001 assert(createMatcher.isMatcher(endsWith));1002 assert.equals(endsWith.toString(), "endsWith([2,3])");1003 });1004 it("matches arrays ending with the same elements", function () {1005 assert(createMatcher.array.endsWith([2]).test([1, 2]));1006 assert(createMatcher.array.endsWith([1, 2]).test([1, 2]));1007 assert.isFalse(1008 createMatcher.array.endsWith([1, 2, 3]).test([1, 2])1009 );1010 assert.isFalse(createMatcher.array.endsWith([3]).test([1, 2]));1011 });1012 it("fails when passed a non-array object", function () {1013 var endsWith = createMatcher.array.endsWith(["two", "three"]);1014 assert.isFalse(1015 endsWith.test({ 0: "one", 1: "two", 2: "three", length: 3 })1016 );1017 });1018 });1019 describe("array.contains", function () {1020 it("has a .contains matcher", function () {1021 var contains = createMatcher.array.contains([2, 3]);1022 assert(createMatcher.isMatcher(contains));1023 assert.equals(contains.toString(), "contains([2,3])");1024 });1025 it("matches arrays containing all the expected elements", function () {1026 assert(createMatcher.array.contains([2]).test([1, 2, 3]));1027 assert(createMatcher.array.contains([1, 2]).test([1, 2]));1028 assert.isFalse(1029 createMatcher.array.contains([1, 2, 3]).test([1, 2])1030 );1031 assert.isFalse(createMatcher.array.contains([3]).test([1, 2]));1032 });1033 it("fails when passed a non-array object", function () {1034 var contains = createMatcher.array.contains(["one", "three"]);1035 assert.isFalse(1036 contains.test({ 0: "one", 1: "two", 2: "three", length: 3 })1037 );1038 });1039 });1040 });1041 describe(".map", function () {1042 it("is typeOf map matcher", function () {1043 var map = createMatcher.map;1044 assert(createMatcher.isMatcher(map));1045 assert.equals(map.toString(), 'typeOf("map")');1046 });1047 describe("map.deepEquals", function () {1048 if (typeof Map === "function") {1049 it("has a .deepEquals matcher", function () {1050 var mapOne = new Map();1051 mapOne.set("one", 1);1052 mapOne.set("two", 2);1053 mapOne.set("three", 3);1054 var deepEquals = createMatcher.map.deepEquals(mapOne);1055 assert(createMatcher.isMatcher(deepEquals));1056 assert.equals(1057 deepEquals.toString(),1058 "deepEquals(Map[['one',1],['two',2],['three',3]])"1059 );1060 });1061 it("matches maps with the exact same elements", function () {1062 var mapOne = new Map();1063 mapOne.set("one", 1);1064 mapOne.set("two", 2);1065 mapOne.set("three", 3);1066 var mapTwo = new Map();1067 mapTwo.set("one", 1);1068 mapTwo.set("two", 2);1069 mapTwo.set("three", 3);1070 var mapThree = new Map();1071 mapThree.set("one", 1);1072 mapThree.set("two", 2);1073 var deepEquals = createMatcher.map.deepEquals(mapOne);1074 assert(deepEquals.test(mapTwo));1075 assert.isFalse(deepEquals.test(mapThree));1076 assert.isFalse(deepEquals.test(new Map()));1077 });1078 it("fails when maps have the same keys but different values", function () {1079 var mapOne = new Map();1080 mapOne.set("one", 1);1081 mapOne.set("two", 2);1082 mapOne.set("three", 3);1083 var mapTwo = new Map();1084 mapTwo.set("one", 2);1085 mapTwo.set("two", 4);1086 mapTwo.set("three", 8);1087 var mapThree = new Map();1088 mapTwo.set("one", 1);1089 mapTwo.set("two", 2);1090 mapTwo.set("three", 4);1091 var deepEquals = createMatcher.map.deepEquals(mapOne);1092 assert.isFalse(deepEquals.test(mapTwo));1093 assert.isFalse(deepEquals.test(mapThree));1094 });1095 it("fails when passed a non-map object", function () {1096 var deepEquals = createMatcher.array.deepEquals(new Map());1097 assert.isFalse(deepEquals.test({}));1098 assert.isFalse(deepEquals.test([]));1099 });1100 }1101 });1102 describe("map.contains", function () {1103 if (typeof Map === "function") {1104 it("has a .contains matcher", function () {1105 var mapOne = new Map();1106 mapOne.set("one", 1);1107 mapOne.set("two", 2);1108 mapOne.set("three", 3);1109 var contains = createMatcher.map.contains(mapOne);1110 assert(createMatcher.isMatcher(contains));1111 assert.equals(1112 contains.toString(),1113 "contains(Map[['one',1],['two',2],['three',3]])"1114 );1115 });1116 it("matches maps containing the given elements", function () {1117 var mapOne = new Map();1118 mapOne.set("one", 1);1119 mapOne.set("two", 2);1120 mapOne.set("three", 3);1121 var mapTwo = new Map();1122 mapTwo.set("one", 1);1123 mapTwo.set("two", 2);1124 mapTwo.set("three", 3);1125 var mapThree = new Map();1126 mapThree.set("one", 1);1127 mapThree.set("two", 2);1128 var mapFour = new Map();1129 mapFour.set("one", 1);1130 mapFour.set("four", 4);1131 assert(createMatcher.map.contains(mapTwo).test(mapOne));1132 assert(createMatcher.map.contains(mapThree).test(mapOne));1133 assert.isFalse(1134 createMatcher.map.contains(mapFour).test(mapOne)1135 );1136 });1137 it("fails when maps contain the same keys but different values", function () {1138 var mapOne = new Map();1139 mapOne.set("one", 1);1140 mapOne.set("two", 2);1141 mapOne.set("three", 3);1142 var mapTwo = new Map();1143 mapTwo.set("one", 2);1144 mapTwo.set("two", 4);1145 mapTwo.set("three", 8);1146 var mapThree = new Map();1147 mapThree.set("one", 1);1148 mapThree.set("two", 2);1149 mapThree.set("three", 4);1150 assert.isFalse(1151 createMatcher.map.contains(mapTwo).test(mapOne)1152 );1153 assert.isFalse(1154 createMatcher.map.contains(mapThree).test(mapOne)1155 );1156 });1157 it("fails when passed a non-map object", function () {1158 var contains = createMatcher.map.contains(new Map());1159 assert.isFalse(contains.test({}));1160 assert.isFalse(contains.test([]));1161 });1162 }1163 });1164 });1165 describe(".set", function () {1166 it("is typeOf set matcher", function () {1167 var set = createMatcher.set;1168 assert(createMatcher.isMatcher(set));1169 assert.equals(set.toString(), 'typeOf("set")');1170 });1171 describe("set.deepEquals", function () {1172 if (typeof Set === "function") {1173 it("has a .deepEquals matcher", function () {1174 var setOne = new Set();1175 setOne.add("one");1176 setOne.add("two");1177 setOne.add("three");1178 var deepEquals = createMatcher.set.deepEquals(setOne);1179 assert(createMatcher.isMatcher(deepEquals));1180 assert.equals(1181 deepEquals.toString(),1182 "deepEquals(Set['one','two','three'])"1183 );1184 });1185 it("matches sets with the exact same elements", function () {1186 var setOne = new Set();1187 setOne.add("one");1188 setOne.add("two");1189 setOne.add("three");1190 var setTwo = new Set();1191 setTwo.add("one");1192 setTwo.add("two");1193 setTwo.add("three");1194 var setThree = new Set();1195 setThree.add("one");1196 setThree.add("two");1197 var deepEquals = createMatcher.set.deepEquals(setOne);1198 assert(deepEquals.test(setTwo));1199 assert.isFalse(deepEquals.test(setThree));1200 assert.isFalse(deepEquals.test(new Set()));1201 });1202 it("fails when passed a non-set object", function () {1203 var deepEquals = createMatcher.array.deepEquals(new Set());1204 assert.isFalse(deepEquals.test({}));1205 assert.isFalse(deepEquals.test([]));1206 });1207 }1208 });1209 describe("set.contains", function () {1210 if (typeof Set === "function") {1211 it("has a .contains matcher", function () {1212 var setOne = new Set();1213 setOne.add("one");1214 setOne.add("two");1215 setOne.add("three");1216 var contains = createMatcher.set.contains(setOne);1217 assert(createMatcher.isMatcher(contains));1218 assert.equals(1219 contains.toString(),1220 "contains(Set['one','two','three'])"1221 );1222 });1223 it("matches sets containing the given elements", function () {1224 var setOne = new Set();1225 setOne.add("one");1226 setOne.add("two");1227 setOne.add("three");1228 var setTwo = new Set();1229 setTwo.add("one");1230 setTwo.add("two");1231 setTwo.add("three");1232 var setThree = new Set();1233 setThree.add("one");1234 setThree.add("two");1235 var setFour = new Set();1236 setFour.add("one");1237 setFour.add("four");1238 assert(createMatcher.set.contains(setTwo).test(setOne));1239 assert(createMatcher.set.contains(setThree).test(setOne));1240 assert.isFalse(1241 createMatcher.set.contains(setFour).test(setOne)1242 );1243 });1244 it("fails when passed a non-set object", function () {1245 var contains = createMatcher.set.contains(new Set());1246 assert.isFalse(contains.test({}));1247 assert.isFalse(contains.test([]));1248 });1249 }1250 });1251 });1252 describe(".regexp", function () {1253 it("is typeOf regexp matcher", function () {1254 var regexp = createMatcher.regexp;1255 assert(createMatcher.isMatcher(regexp));1256 assert.equals(regexp.toString(), 'typeOf("regexp")');1257 });1258 });1259 describe(".date", function () {1260 it("is typeOf regexp matcher", function () {1261 var date = createMatcher.date;1262 assert(createMatcher.isMatcher(date));1263 assert.equals(date.toString(), 'typeOf("date")');1264 });1265 });1266 describe(".symbol", function () {1267 it("is typeOf symbol matcher", function () {1268 var symbol = createMatcher.symbol;1269 assert(createMatcher.isMatcher(symbol));1270 assert.equals(symbol.toString(), 'typeOf("symbol")');1271 });1272 });1273 describe(".or", function () {1274 it("is matcher", function () {1275 var numberOrString = createMatcher.number.or(createMatcher.string);1276 assert(createMatcher.isMatcher(numberOrString));1277 assert.equals(1278 numberOrString.toString(),1279 'typeOf("number").or(typeOf("string"))'1280 );1281 });1282 it("requires matcher argument", function () {1283 assert.exception(1284 function () {1285 createMatcher.instanceOf(Error).or();1286 },1287 { name: "TypeError" }1288 );1289 });1290 it("will coerce argument to matcher", function () {1291 var abcOrDef = createMatcher("abc").or("def");1292 assert(createMatcher.isMatcher(abcOrDef));1293 assert.equals(abcOrDef.toString(), 'match("abc").or(match("def"))');1294 });1295 it("returns true if either matcher matches", function () {1296 var numberOrString = createMatcher.number.or(createMatcher.string);1297 assert(numberOrString.test(123));1298 assert(numberOrString.test("abc"));1299 });1300 it("returns false if neither matcher matches", function () {1301 var numberOrAbc = createMatcher.number.or("abc");1302 assert.isFalse(numberOrAbc.test(/.+/));1303 assert.isFalse(numberOrAbc.test(new Date()));1304 assert.isFalse(numberOrAbc.test({}));1305 });1306 it("can be used with undefined", function () {1307 var numberOrUndef = createMatcher.number.or(undefined);1308 assert(numberOrUndef.test(123));1309 assert(numberOrUndef.test(undefined));1310 });1311 });1312 describe(".and", function () {1313 it("is matcher", function () {1314 var fooAndBar = createMatcher1315 .has("foo")1316 .and(createMatcher.has("bar"));1317 assert(createMatcher.isMatcher(fooAndBar));1318 assert.equals(fooAndBar.toString(), 'has("foo").and(has("bar"))');1319 });1320 it("requires matcher argument", function () {1321 assert.exception(1322 function () {1323 createMatcher.instanceOf(Error).and();1324 },1325 { name: "TypeError" }1326 );1327 });1328 it("will coerce to matcher", function () {1329 var abcOrObj = createMatcher("abc").or({ a: 1 });1330 assert(createMatcher.isMatcher(abcOrObj));1331 assert.equals(abcOrObj.toString(), 'match("abc").or(match(a: 1))');1332 });1333 it("returns true if both matchers match", function () {1334 var fooAndBar = createMatcher.has("foo").and({ bar: "bar" });1335 assert(fooAndBar.test({ foo: "foo", bar: "bar" }));1336 });1337 it("returns false if either matcher does not match", function () {1338 var fooAndBar = createMatcher1339 .has("foo")1340 .and(createMatcher.has("bar"));1341 assert.isFalse(fooAndBar.test({ foo: "foo" }));1342 assert.isFalse(fooAndBar.test({ bar: "bar" }));1343 });1344 it("can be used with undefined", function () {1345 var falsyAndUndefined = createMatcher.falsy.and(undefined);1346 assert.isFalse(falsyAndUndefined.test(false));1347 assert(falsyAndUndefined.test(undefined));1348 });1349 });1350 describe("nested", function () {1351 it("returns true for an object with nested matcher", function () {1352 var match = createMatcher({1353 outer: createMatcher({ inner: "sinon" }),1354 });1355 assert.isTrue(1356 match.test({ outer: { inner: "sinon", foo: "bar" } })1357 );1358 });1359 it("returns true for an array of nested matchers", function () {1360 var match = createMatcher([createMatcher({ str: "sinon" })]);1361 assert.isTrue(match.test([{ str: "sinon", foo: "bar" }]));1362 });1363 it("returns true for an object containing a matching array of nested matchers", function () {1364 var match = createMatcher({1365 deep: { nested: [createMatcher({ partial: "yes" })] },1366 });1367 assert.isTrue(1368 match.test({1369 deep: { nested: [{ partial: "yes", other: "ok" }] },1370 })1371 );1372 });1373 it("returns false for an object containing a non matching array of nested matchers", function () {1374 var match = createMatcher({1375 deep: { nested: [createMatcher({ partial: "no" })] },1376 });1377 assert.isFalse(1378 match.test({1379 deep: { nested: [{ partial: "yes", other: "ok" }] },1380 })1381 );1382 });1383 });...
create-matcher.js
Source:create-matcher.js
...26 * @param {*} expectation An expecttation27 * @param {string} message A message for the expectation28 * @returns {object} A matcher object29 */30function createMatcher(expectation, message) {31 var m = Object.create(matcherPrototype);32 var type = typeOf(expectation);33 if (message !== undefined && typeof message !== "string") {34 throw new TypeError("Message should be a string");35 }36 if (arguments.length > 2) {37 throw new TypeError(38 `Expected 1 or 2 arguments, received ${arguments.length}`39 );40 }41 if (type in TYPE_MAP) {42 TYPE_MAP[type](m, expectation, message);43 } else {44 m.test = function (actual) {45 return deepEqual(actual, expectation);46 };47 }48 if (!m.message) {49 m.message = `match(${valueToString(expectation)})`;50 }51 return m;52}53createMatcher.isMatcher = isMatcher;54createMatcher.any = createMatcher(function () {55 return true;56}, "any");57createMatcher.defined = createMatcher(function (actual) {58 return actual !== null && actual !== undefined;59}, "defined");60createMatcher.truthy = createMatcher(function (actual) {61 return Boolean(actual);62}, "truthy");63createMatcher.falsy = createMatcher(function (actual) {64 return !actual;65}, "falsy");66createMatcher.same = function (expectation) {67 return createMatcher(function (actual) {68 return expectation === actual;69 }, `same(${valueToString(expectation)})`);70};71createMatcher.in = function (arrayOfExpectations) {72 if (typeOf(arrayOfExpectations) !== "array") {73 throw new TypeError("array expected");74 }75 return createMatcher(function (actual) {76 return some(arrayOfExpectations, function (expectation) {77 return expectation === actual;78 });79 }, `in(${valueToString(arrayOfExpectations)})`);80};81createMatcher.typeOf = function (type) {82 assertType(type, "string", "type");83 return createMatcher(function (actual) {84 return typeOf(actual) === type;85 }, `typeOf("${type}")`);86};87createMatcher.instanceOf = function (type) {88 /* istanbul ignore if */89 if (90 typeof Symbol === "undefined" ||91 typeof Symbol.hasInstance === "undefined"92 ) {93 assertType(type, "function", "type");94 } else {95 assertMethodExists(96 type,97 Symbol.hasInstance,98 "type",99 "[Symbol.hasInstance]"100 );101 }102 return createMatcher(function (actual) {103 return actual instanceof type;104 }, `instanceOf(${functionName(type) || objectToString(type)})`);105};106/**107 * Creates a property matcher108 *109 * @private110 * @param {Function} propertyTest A function to test the property against a value111 * @param {string} messagePrefix A prefix to use for messages generated by the matcher112 * @returns {object} A matcher113 */114function createPropertyMatcher(propertyTest, messagePrefix) {115 return function (property, value) {116 assertType(property, "string", "property");117 var onlyProperty = arguments.length === 1;118 var message = `${messagePrefix}("${property}"`;119 if (!onlyProperty) {120 message += `, ${valueToString(value)}`;121 }122 message += ")";123 return createMatcher(function (actual) {124 if (125 actual === undefined ||126 actual === null ||127 !propertyTest(actual, property)128 ) {129 return false;130 }131 return onlyProperty || deepEqual(actual[property], value);132 }, message);133 };134}135createMatcher.has = createPropertyMatcher(function (actual, property) {136 if (typeof actual === "object") {137 return property in actual;138 }139 return actual[property] !== undefined;140}, "has");141createMatcher.hasOwn = createPropertyMatcher(function (actual, property) {142 return hasOwnProperty(actual, property);143}, "hasOwn");144createMatcher.hasNested = function (property, value) {145 assertType(property, "string", "property");146 var onlyProperty = arguments.length === 1;147 var message = `hasNested("${property}"`;148 if (!onlyProperty) {149 message += `, ${valueToString(value)}`;150 }151 message += ")";152 return createMatcher(function (actual) {153 if (154 actual === undefined ||155 actual === null ||156 get(actual, property) === undefined157 ) {158 return false;159 }160 return onlyProperty || deepEqual(get(actual, property), value);161 }, message);162};163var jsonParseResultTypes = {164 null: true,165 boolean: true,166 number: true,167 string: true,168 object: true,169 array: true,170};171createMatcher.json = function (value) {172 if (!jsonParseResultTypes[typeOf(value)]) {173 throw new TypeError("Value cannot be the result of JSON.parse");174 }175 var message = `json(${JSON.stringify(value, null, " ")})`;176 return createMatcher(function (actual) {177 var parsed;178 try {179 parsed = JSON.parse(actual);180 } catch (e) {181 return false;182 }183 return deepEqual(parsed, value);184 }, message);185};186createMatcher.every = function (predicate) {187 assertMatcher(predicate);188 return createMatcher(function (actual) {189 if (typeOf(actual) === "object") {190 return every(Object.keys(actual), function (key) {191 return predicate.test(actual[key]);192 });193 }194 return (195 isIterable(actual) &&196 every(actual, function (element) {197 return predicate.test(element);198 })199 );200 }, `every(${predicate.message})`);201};202createMatcher.some = function (predicate) {203 assertMatcher(predicate);204 return createMatcher(function (actual) {205 if (typeOf(actual) === "object") {206 return !every(Object.keys(actual), function (key) {207 return !predicate.test(actual[key]);208 });209 }210 return (211 isIterable(actual) &&212 !every(actual, function (element) {213 return !predicate.test(element);214 })215 );216 }, `some(${predicate.message})`);217};218createMatcher.array = createMatcher.typeOf("array");219createMatcher.array.deepEquals = function (expectation) {220 return createMatcher(function (actual) {221 // Comparing lengths is the fastest way to spot a difference before iterating through every item222 var sameLength = actual.length === expectation.length;223 return (224 typeOf(actual) === "array" &&225 sameLength &&226 every(actual, function (element, index) {227 var expected = expectation[index];228 return typeOf(expected) === "array" &&229 typeOf(element) === "array"230 ? createMatcher.array.deepEquals(expected).test(element)231 : deepEqual(expected, element);232 })233 );234 }, `deepEquals([${iterableToString(expectation)}])`);235};236createMatcher.array.startsWith = function (expectation) {237 return createMatcher(function (actual) {238 return (239 typeOf(actual) === "array" &&240 every(expectation, function (expectedElement, index) {241 return actual[index] === expectedElement;242 })243 );244 }, `startsWith([${iterableToString(expectation)}])`);245};246createMatcher.array.endsWith = function (expectation) {247 return createMatcher(function (actual) {248 // This indicates the index in which we should start matching249 var offset = actual.length - expectation.length;250 return (251 typeOf(actual) === "array" &&252 every(expectation, function (expectedElement, index) {253 return actual[offset + index] === expectedElement;254 })255 );256 }, `endsWith([${iterableToString(expectation)}])`);257};258createMatcher.array.contains = function (expectation) {259 return createMatcher(function (actual) {260 return (261 typeOf(actual) === "array" &&262 every(expectation, function (expectedElement) {263 return arrayIndexOf(actual, expectedElement) !== -1;264 })265 );266 }, `contains([${iterableToString(expectation)}])`);267};268createMatcher.map = createMatcher.typeOf("map");269createMatcher.map.deepEquals = function mapDeepEquals(expectation) {270 return createMatcher(function (actual) {271 // Comparing lengths is the fastest way to spot a difference before iterating through every item272 var sameLength = actual.size === expectation.size;273 return (274 typeOf(actual) === "map" &&275 sameLength &&276 every(actual, function (element, key) {277 return expectation.has(key) && expectation.get(key) === element;278 })279 );280 }, `deepEquals(Map[${iterableToString(expectation)}])`);281};282createMatcher.map.contains = function mapContains(expectation) {283 return createMatcher(function (actual) {284 return (285 typeOf(actual) === "map" &&286 every(expectation, function (element, key) {287 return actual.has(key) && actual.get(key) === element;288 })289 );290 }, `contains(Map[${iterableToString(expectation)}])`);291};292createMatcher.set = createMatcher.typeOf("set");293createMatcher.set.deepEquals = function setDeepEquals(expectation) {294 return createMatcher(function (actual) {295 // Comparing lengths is the fastest way to spot a difference before iterating through every item296 var sameLength = actual.size === expectation.size;297 return (298 typeOf(actual) === "set" &&299 sameLength &&300 every(actual, function (element) {301 return expectation.has(element);302 })303 );304 }, `deepEquals(Set[${iterableToString(expectation)}])`);305};306createMatcher.set.contains = function setContains(expectation) {307 return createMatcher(function (actual) {308 return (309 typeOf(actual) === "set" &&310 every(expectation, function (element) {311 return actual.has(element);312 })313 );314 }, `contains(Set[${iterableToString(expectation)}])`);315};316createMatcher.bool = createMatcher.typeOf("boolean");317createMatcher.number = createMatcher.typeOf("number");318createMatcher.string = createMatcher.typeOf("string");319createMatcher.object = createMatcher.typeOf("object");320createMatcher.func = createMatcher.typeOf("function");321createMatcher.regexp = createMatcher.typeOf("regexp");...
matcher.test.js
Source:matcher.test.js
...66 });67 });68 describe('createMatcher', function() {69 it('should return an instance of MatchingMessageHandler', function() {70 const matcher = createMatcher({match: 'foo', handleMessage: []});71 expect(matcher).to.be.an.instanceof(MatchingMessageHandler);72 });73 });74 describe('MatchingMessageHandler', function() {75 describe('constructor', function() {76 it('should behave like DelegatingMessageHandler', function() {77 expect(() => createMatcher({match: 'foo'}, nop)).to.not.throw();78 expect(() => createMatcher({match: 'foo'})).to.throw(/missing.*message.*handler/i);79 });80 it('should throw if no match option was specified', function() {81 expect(() => createMatcher(nop)).to.throw(/missing.*match/i);82 expect(() => createMatcher({}, nop)).to.throw(/missing.*match/i);83 expect(() => createMatcher({match: 'foo'}, nop)).to.not.throw();84 expect(() => createMatcher({match() {}}, nop)).to.not.throw();85 });86 });87 describe('handleMessage', function() {88 it('should return a promise that gets fulfilled', function() {89 const matcher = createMatcher({match: 'foo'}, nop);90 return expect(matcher.handleMessage()).to.be.fulfilled();91 });92 it('should accept a match string', function() {93 const handleMessage = (remainder, arg) => ({message: `${remainder} ${arg}`});94 const matcher = createMatcher({match: 'foo', handleMessage});95 return Promise.all([96 expect(matcher.handleMessage('foo', 1)).to.become({message: ' 1'}),97 expect(matcher.handleMessage('foo bar', 1)).to.become({message: 'bar 1'}),98 expect(matcher.handleMessage('foo bar', 1)).to.become({message: 'bar 1'}),99 expect(matcher.handleMessage('foo-bar', 1)).to.become(false),100 ]);101 });102 it('should accept a match regex', function() {103 const handleMessage = (remainder, arg) => ({message: `${remainder} ${arg}`});104 const matcher = createMatcher({match: /^foo(?:$|\s+(.*))/, handleMessage});105 return Promise.all([106 expect(matcher.handleMessage('foo', 1)).to.become({message: ' 1'}),107 expect(matcher.handleMessage('foo bar', 1)).to.become({message: 'bar 1'}),108 expect(matcher.handleMessage('foo bar', 1)).to.become({message: 'bar 1'}),109 expect(matcher.handleMessage('foo-bar', 1)).to.become(false),110 ]);111 });112 it('should accept a match function', function() {113 const handleMessage = (remainder, arg) => ({message: `${remainder} ${arg}`});114 const match = message => {115 const [fullMatch, capture = ''] = message.match(/^foo(?:$|\s+(.*))/) || [];116 return fullMatch ? capture : false;117 };118 const matcher = createMatcher({match, handleMessage});119 return Promise.all([120 expect(matcher.handleMessage('foo', 1)).to.become({message: ' 1'}),121 expect(matcher.handleMessage('foo bar', 1)).to.become({message: 'bar 1'}),122 expect(matcher.handleMessage('foo bar', 1)).to.become({message: 'bar 1'}),123 expect(matcher.handleMessage('foo-bar', 1)).to.become(false),124 ]);125 });126 it('should only run child handlers on match / should return false on no match', function() {127 let i = 0;128 const handleMessage = () => {129 i++;130 return {message: 'yay'};131 };132 const matcher = createMatcher({match: 'foo', handleMessage});133 return Promise.mapSeries([134 () => expect(matcher.handleMessage('foo')).to.become({message: 'yay'}),135 () => expect(matcher.handleMessage('baz')).to.become(false),136 () => expect(i).to.equal(1),137 ], f => f());138 });139 it('should support function matching / should pass message and additional arguments into match fn', function() {140 const match = (message, arg) => {141 const [greeting, remainder] = message.split(' ');142 return greeting === 'hello' ? `the ${remainder} is ${arg}` : false;143 };144 const handleMessage = (remainder, arg) => ({message: `${remainder}, ${arg}`});145 const matcher = createMatcher({match, handleMessage});146 return Promise.all([147 expect(matcher.handleMessage('hello world', 'me')).to.become({message: 'the world is me, me'}),148 expect(matcher.handleMessage('hello universe', 'me')).to.become({message: 'the universe is me, me'}),149 expect(matcher.handleMessage('goodbye world', 'me')).to.become(false),150 expect(matcher.handleMessage('goodbye universe', 'me')).to.become(false),151 ]);152 });153 it('should reject if the match option is invalid', function() {154 const matcher = createMatcher({match: 123, handleMessage() {}});155 return expect(matcher.handleMessage('foo')).to.be.rejectedWith(/invalid.*match/i);156 });157 it('should reject if the match function throws an exception', function() {158 const match = message => { throw new Error(`whoops ${message}`); };159 const matcher = createMatcher({match, handleMessage() {}});160 return expect(matcher.handleMessage('foo')).to.be.rejectedWith('whoops foo');161 });162 });163 });...
Using AI Code Generation
1var assert = require('assert');2var sinon = require('sinon');3var myObj = {4 myMethod: function(arg1, arg2) {5 }6};7var spy = sinon.spy(myObj, 'myMethod');8myObj.myMethod('foo', 'bar');9assert(spy.calledWith(sinon.match.string, sinon.match.string));10assert(spy.calledWith('foo', sinon.match.string));11assert(spy.calledWith(sinon.match.string, 'bar'));12assert(spy.calledWith(sinon.match.string, sinon.match.same('bar')));13assert(spy.calledWith(sinon.match.string, sinon.match.typeOf('string')));14assert(spy.calledWith(sinon.match.string, sinon.match.instanceOf(Object)));15assert(spy.calledWith(sinon.match.string, sinon.match.has('foo', 'bar')));16assert(spy.calledWith(sinon.match.string, sinon.match.hasOwn('foo', 'bar')));17assert(spy.calledWith(sinon.match.string, sinon.match.has('foo', sinon.match.string)));18assert(spy.calledWith(sinon.match.string, sinon.match.has('foo', sinon.match.has('bar', 'baz'))));19assert(spy.calledWith(sinon.match.string, sinon.match.has('foo', sinon.match.has('bar', sinon.match.same('baz')))));20assert(spy.calledWith(sinon.match.string, sinon.match.has('foo', sinon.match.has('bar', sinon.match.defined))));21assert(spy.calledWith(sinon.match.string, sinon.match.has('foo', sinon.match.has('bar', sinon.match.truthy))));22assert(spy.calledWith(sinon.match.string, sinon.match.has('foo', sinon.match.has('bar', sinon.match.falsy))));23assert(spy.calledWith(sinon.match.string, sinon.match.has('foo', sinon.match.has('bar', sinon.match.bool))));24assert(spy.calledWith(sinon.match.string, sinon.match.has('foo', sinon.match.has('bar', sinon.match.number))));25assert(spy.calledWith(sinon.match.string, sinon.match.has('foo', sinon.match.has('bar', sinon.match.string))));26assert(spy.calledWith(sinon.match.string, sinon.match.has('foo', sinon.match.has('bar', sinon.match.object))));27assert(spy.calledWith(sinon.match.string, sinon.match.has('foo', sinon.match.has('bar', sinon.match.func))));28assert(spy.calledWith(sinon.match.string, sinon.match.has('foo', sinon.match.has('bar', sinon
Using AI Code Generation
1const sinon = require('sinon');2const myObj = {3 myMethod: function () {4 return 1;5 }6};7const mySpy = sinon.spy(myObj, 'myMethod');8myObj.myMethod();9const sinon = require('sinon');10const myObj = {11 myMethod: function () {12 return 1;13 }14};15const mySpy = sinon.spy(myObj, 'myMethod');16myObj.myMethod();17const sinon = require('sinon');18const myObj = {19 myMethod: function () {20 return 1;21 }22};23const mySpy = sinon.spy(myObj, 'myMethod');24myObj.myMethod();25const sinon = require('sinon');26const myObj = {27 myMethod: function () {28 return 1;29 }30};31const mySpy = sinon.spy(myObj, 'myMethod');32myObj.myMethod();33console.log(mySpy.calledWith(
Using AI Code Generation
1var sinon = require('sinon');2var matcher = sinon.match.createMatcher(function (value) {3 return value && value.foo === 'bar';4});5var obj = { foo: 'bar', bar: 'foo' };6var sinon = require('sinon');7var obj = sinon.createStubInstance(SomeConstructor);8var sinon = require('sinon');9var server = sinon.fakeServer.create();10server.respondWith("GET", "/test", [200, { "Content-Type": "text/plain" }, "Hello, World!"]);11server.respondWith("POST", "/echo", function (xhr) {12 xhr.respond(200, { "Content-Type": "text/plain" }, xhr.requestBody);13});14var xhr = new XMLHttpRequest();15xhr.open("GET", "/test");16xhr.send();17xhr.onload = function () {18};19var xhr2 = new XMLHttpRequest();20xhr2.open("POST", "/echo");21xhr2.send("Hello, World!");22xhr2.onload = function () {23};24var sinon = require('sinon');25var clock = sinon.fakeTimers.create();26clock.tick(100);27clock.restore();28var sinon = require('sinon');29var request = sinon.useFakeXMLHttpRequest();30var requests = [];31request.onCreate = function (xhr) {32 requests.push(xhr);33};34request.restore();35var sinon = require('sinon');36var request = sinon.useFakeXMLHttpRequest();37var requests = [];38request.onCreate = function (xhr
Using AI Code Generation
1var sinon = require('sinon');2var matcher = sinon.createMatcher(function (actual) {3 return actual > 10;4});5var spy = sinon.spy();6spy(11);7spy(9);8var sinon = require('sinon');9var Person = function () {10 this.setName = function (name) {11 this.name = name;12 };13 this.getName = function () {14 return this.name;15 };16};17var person = sinon.createStubInstance(Person);18person.setName('John');19person.getName.returns('Doe');20var sinon = require('sinon');21var server = sinon.fakeServer.create();22server.respondWith('GET', '/api', [200, { 'Content-Type': 'application/json' }, '{ "data": "test" }']);23var xhr = new XMLHttpRequest();24xhr.open('GET', '/api');25xhr.send();26server.respond();27var sinon = require('sinon');28var clock = sinon.useFakeTimers();29var timerCallback = sinon.spy();30var timer = setTimeout(timerCallback, 100);31clock.tick(101);32var sinon = require('sinon');33var clock = sinon.useFakeTimers();34var timerCallback = sinon.spy();35var timer = setTimeout(timerCallback, 100);36clock.tick(101);37var sinon = require('sinon');38var clock = sinon.useFakeTimers();39var timerCallback = sinon.spy();40var timer = setTimeout(timerCallback, 100);41clock.tick(101);42var sinon = require('sinon');43var clock = sinon.useFakeTimers();44var timerCallback = sinon.spy();45var timer = setTimeout(timer
Using AI Code Generation
1var sinon = require('sinon');2var assert = require('assert');3var myObj = {4 myMethod: function () {5 return "hello";6 }7};8var spy = sinon.spy(myObj, "myMethod");9myObj.myMethod();10assert(spy.called);11assert(spy.calledOnce);12assert(spy.calledWith("hello"));13var sinon = require('sinon');14var assert = require('assert');15var stub = sinon.createStubInstance(Date);16stub.toUTCString();17assert(stub.toUTCString.called);18assert(stub.toUTCString.calledOnce);19var sinon = require('sinon');20var assert = require('assert');21var stub = sinon.createStubInstance(Date);22stub.toUTCString();23assert(stub.toUTCString.called);24assert(stub.toUTCString.calledOnce);25var sinon = require('sinon');26var server = sinon.fakeServer.create();27server.respondWith("GET", "/test", [200, { "Content-Type": "text/plain" }, "Hello, World!"]);28server.respond();29assert(server.respond.called);30assert(server.respond.calledOnce);31assert(server.respond.calledWith("GET", "/test", [200, { "Content-Type": "text/plain" }, "Hello, World!"]));32var sinon = require('sinon');33var clock = sinon.useFakeTimers();34clock.tick(100);35assert(clock.tick.called);
Using AI Code Generation
1var matcher = sinon.createMatcher(function (text) {2 return text.indexOf('match') !== -1;3});4var stub = sinon.createStubInstance(MyClass);5var spyCall = sinon.spyCall({ func: function () { } }, [], this);6var spyCall = sinon.spyCall({ func: function () { } }, [], this);7var stub = sinon.stub(object, "method", func);8var stub = sinon.stub(object, "method", func);9var stub = sinon.stub(object, "method", func);10var stub = sinon.stub(object, "method", func);11var stub = sinon.stub(object, "method", func);12var stub = sinon.stub(object, "method", func);13var stub = sinon.stub(object, "method", func);14var stub = sinon.stub(object, "method", func);15var stub = sinon.stub(object, "method", func);16var stub = sinon.stub(object, "method", func);17var stub = sinon.stub(object, "method", func);18var stub = sinon.stub(object, "method", func);19var stub = sinon.stub(object, "method", func);20var stub = sinon.stub(object, "method", func);21var stub = sinon.stub(object, "method", func);22var stub = sinon.stub(object, "method", func);23var stub = sinon.stub(object, "method", func);24var stub = sinon.stub(object, "method", func);25var stub = sinon.stub(object, "method", func);
Using AI Code Generation
1var createMatcher = sinon.createMatcher;2var stub = sinon.stub();3stub(createMatcher(function(arg) {4 return arg === 'hello';5}));6var createStubInstance = sinon.createStubInstance;7var stub = createStubInstance(Date);8stub.toISOString.returns('2015-01-01T00:00:00.000Z');9var fakeServerWithClock = sinon.fakeServerWithClock;10var clock = fakeServerWithClock.create();11clock.tick(1000);12clock.restore();13var fakeServer = sinon.fakeServer;14var server = fakeServer.create();15server.respondWith('GET', '/', [200, { 'Content-Type': 'text/plain' }, 'OK']);16server.respond();17var fake = sinon.fake;18var callback = fake();19callback();20var fakeServerWithClock = sinon.fakeServerWithClock;21var clock = fakeServerWithClock.create();22clock.tick(1000);23clock.restore();24var fakeServer = sinon.fakeServer;25var server = fakeServer.create();26server.respondWith('GET', '/', [200, { 'Content-Type': 'text/plain' }, 'OK']);27server.respond();28var fake = sinon.fake;29var callback = fake();30callback();31var fakeServerWithClock = sinon.fakeServerWithClock;32var clock = fakeServerWithClock.create();33clock.tick(1000);34clock.restore();35var fakeServer = sinon.fakeServer;36var server = fakeServer.create();37server.respondWith('
Using AI Code Generation
1describe('toBeTested', () => {2 it('should return true if the value is a string', () => {3 const result = toBeTested('string');4 expect(result).to.be.true;5 });6 it('should return false if the value is not a string', () => {7 const result = toBeTested(123);8 expect(result).to.be.false;9 });10});11module.exports = function toBeTested(value) {12 return typeof value === 'string';13};
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!