How to use spy method in Cypress

Best JavaScript code snippet using cypress

spy_test.js

Source:spy_test.js Github

copy

Full Screen

...20            "returns false if spy was not called": function () {21                assert.isFalse(this.spy[method](1, 2, 3));22            },23            "returns true if spy was called with args": function () {24                this.spy(1, 2, 3);25                assert(this.spy[method](1, 2, 3));26            },27            "returns true if called with args at least once": function () {28                this.spy(1, 3, 3);29                this.spy(1, 2, 3);30                this.spy(3, 2, 3);31                assert(this.spy[method](1, 2, 3));32            },33            "returns false if not called with args": function () {34                this.spy(1, 3, 3);35                this.spy(2);36                this.spy();37                assert.isFalse(this.spy[method](1, 2, 3));38            },39            "returns true for partial match": function () {40                this.spy(1, 3, 3);41                this.spy(2);42                this.spy();43                assert(this.spy[method](1, 3));44            },45            "matchs all arguments individually, not as array": function () {46                this.spy([1, 2, 3]);47                assert.isFalse(this.spy[method](1, 2, 3));48            },49            "uses matcher": function () {50                this.spy("abc");51                assert(this.spy[method](sinon.match.typeOf("string")));52            },53            "uses matcher in object": function () {54                this.spy({ some: "abc" });55                assert(this.spy[method]({ some: sinon.match.typeOf("string") }));56            }57        };58    }59    function spyAlwaysCalledTests(method) {60        return {61            setUp: function () {62                this.spy = sinon.spy.create();63            },64            "returns false if spy was not called": function () {65                assert.isFalse(this.spy[method](1, 2, 3));66            },67            "returns true if spy was called with args": function () {68                this.spy(1, 2, 3);69                assert(this.spy[method](1, 2, 3));70            },71            "returns false if called with args only once": function () {72                this.spy(1, 3, 3);73                this.spy(1, 2, 3);74                this.spy(3, 2, 3);75                assert.isFalse(this.spy[method](1, 2, 3));76            },77            "returns false if not called with args": function () {78                this.spy(1, 3, 3);79                this.spy(2);80                this.spy();81                assert.isFalse(this.spy[method](1, 2, 3));82            },83            "returns true for partial match": function () {84                this.spy(1, 3, 3);85                assert(this.spy[method](1, 3));86            },87            "returns true for partial match on many calls": function () {88                this.spy(1, 3, 3);89                this.spy(1, 3);90                this.spy(1, 3, 4, 5);91                this.spy(1, 3, 1);92                assert(this.spy[method](1, 3));93            },94            "matchs all arguments individually, not as array": function () {95                this.spy([1, 2, 3]);96                assert.isFalse(this.spy[method](1, 2, 3));97            }98        };99    }100    function spyNeverCalledTests(method) {101        return {102            setUp: function () {103                this.spy = sinon.spy.create();104            },105            "returns true if spy was not called": function () {106                assert(this.spy[method](1, 2, 3));107            },108            "returns false if spy was called with args": function () {109                this.spy(1, 2, 3);110                assert.isFalse(this.spy[method](1, 2, 3));111            },112            "returns false if called with args at least once": function () {113                this.spy(1, 3, 3);114                this.spy(1, 2, 3);115                this.spy(3, 2, 3);116                assert.isFalse(this.spy[method](1, 2, 3));117            },118            "returns true if not called with args": function () {119                this.spy(1, 3, 3);120                this.spy(2);121                this.spy();122                assert(this.spy[method](1, 2, 3));123            },124            "returns false for partial match": function () {125                this.spy(1, 3, 3);126                this.spy(2);127                this.spy();128                assert.isFalse(this.spy[method](1, 3));129            },130            "matchs all arguments individually, not as array": function () {131                this.spy([1, 2, 3]);132                assert(this.spy[method](1, 2, 3));133            }134        };135    }136    buster.testCase("sinon.spy", {137        "does not throw if called without function": function () {138            refute.exception(function () {139                sinon.spy.create();140            });141        },142        "does not throw when calling anonymous spy": function () {143            var spy = sinon.spy.create();144            refute.exception(function () {145                spy();146            });147            assert(spy.called);148        },149        "returns spy function": function () {150            var func = function () {};151            var spy = sinon.spy.create(func);152            assert.isFunction(spy);153            refute.same(func, spy);154        },155        "mirrors custom properties on function": function () {156            var func = function () {};157            func.myProp = 42;158            var spy = sinon.spy.create(func);159            assert.equals(spy.myProp, func.myProp);160        },161        "does not define create method": function () {162            var spy = sinon.spy.create();163            refute.defined(spy.create);164        },165        "does not overwrite original create property": function () {166            var func = function () {};167            var object = func.create = {};168            var spy = sinon.spy.create(func);169            assert.same(spy.create, object);170        },171        "setups logging arrays": function () {172            var spy = sinon.spy.create();173            assert.isArray(spy.args);174            assert.isArray(spy.returnValues);175            assert.isArray(spy.thisValues);176            assert.isArray(spy.exceptions);177        },178        "call": {179            "calls underlying function": function () {180                var called = false;181                var spy = sinon.spy.create(function () {182                    called = true;183                });184                spy();185                assert(called);186            },187            "passs arguments to function": function () {188                var actualArgs;189                var func = function (a, b, c, d) {190                    actualArgs = [a, b, c, d];191                };192                var args = [1, {}, [], ""];193                var spy = sinon.spy.create(func);194                spy(args[0], args[1], args[2], args[3]);195                assert.equals(actualArgs, args);196            },197            "maintains this binding": function () {198                var actualThis;199                var func = function () {200                    actualThis = this;201                };202                var object = {};203                var spy = sinon.spy.create(func);204                spy.call(object);205                assert.same(actualThis, object);206            },207            "returns function's return value": function () {208                var object = {};209                var func = function () {210                    return object;211                };212                var spy = sinon.spy.create(func);213                var actualReturn = spy();214                assert.same(actualReturn, object);215            },216            "throws if function throws": function () {217                var err = new Error();218                var spy = sinon.spy.create(function () {219                    throw err;220                });221                try {222                    spy();223                    buster.assertions.fail("Expected spy to throw exception");224                } catch (e) {225                    assert.same(e, err);226                }227            },228            "retains function length 0": function () {229                var spy = sinon.spy.create(function () {});230                assert.equals(spy.length, 0);231            },232            "retains function length 1": function () {233                var spy = sinon.spy.create(function (a) {});234                assert.equals(spy.length, 1);235            },236            "retains function length 2": function () {237                var spy = sinon.spy.create(function (a, b) {});238                assert.equals(spy.length, 2);239            },240            "retains function length 3": function () {241                var spy = sinon.spy.create(function (a, b, c) {});242                assert.equals(spy.length, 3);243            },244            "retains function length 4": function () {245                var spy = sinon.spy.create(function (a, b, c, d) {});246                assert.equals(spy.length, 4);247            },248            "retains function length 12": function () {249                var spy = sinon.spy.create(function (a, b, c, d, e, f, g, h, i, j,k,l) {});250                assert.equals(spy.length, 12);251            }252        },253        "called": {254            setUp: function () {255                this.spy = sinon.spy.create();256            },257            "is false prior to calling the spy": function () {258                assert.isFalse(this.spy.called);259            },260            "is true after calling the spy once": function () {261                this.spy();262                assert(this.spy.called);263            },264            "is true after calling the spy twice": function () {265                this.spy();266                this.spy();267                assert(this.spy.called);268            }269        },270        "notCalled": {271            setUp: function () {272                this.spy = sinon.spy.create();273            },274            "is true prior to calling the spy": function () {275                assert.isTrue(this.spy.notCalled);276            },277            "is false after calling the spy once": function () {278                this.spy();279                assert.isFalse(this.spy.notCalled);280            }281        },282        "calledOnce": {283            setUp: function () {284                this.spy = sinon.spy.create();285            },286            "is false prior to calling the spy": function () {287                assert.isFalse(this.spy.calledOnce);288            },289            "is true after calling the spy once": function () {290                this.spy();291                assert(this.spy.calledOnce);292            },293            "is false after calling the spy twice": function () {294                this.spy();295                this.spy();296                assert.isFalse(this.spy.calledOnce);297            }298        },299        "calledTwice": {300            setUp: function () {301                this.spy = sinon.spy.create();302            },303            "is false prior to calling the spy": function () {304                assert.isFalse(this.spy.calledTwice);305            },306            "is false after calling the spy once": function () {307                this.spy();308                assert.isFalse(this.spy.calledTwice);309            },310            "is true after calling the spy twice": function () {311                this.spy();312                this.spy();313                assert(this.spy.calledTwice);314            },315            "is false after calling the spy thrice": function () {316                this.spy();317                this.spy();318                this.spy();319                assert.isFalse(this.spy.calledTwice);320            }321        },322        "calledThrice": {323            setUp: function () {324                this.spy = sinon.spy.create();325            },326            "is false prior to calling the spy": function () {327                assert.isFalse(this.spy.calledThrice);328            },329            "is false after calling the spy twice": function () {330                this.spy();331                this.spy();332                assert.isFalse(this.spy.calledThrice);333            },334            "is true after calling the spy thrice": function () {335                this.spy();336                this.spy();337                this.spy();338                assert(this.spy.calledThrice);339            },340            "is false after calling the spy four times": function () {341                this.spy();342                this.spy();343                this.spy();344                this.spy();345                assert.isFalse(this.spy.calledThrice);346            }347        },348        "callCount": {349            setUp: function () {350                this.spy = sinon.spy.create();351            },352            "reports 0 calls": function () {353                assert.equals(this.spy.callCount, 0);354            },355            "records one call": function () {356                this.spy();357                assert.equals(this.spy.callCount, 1);358            },359            "records two calls": function () {360                this.spy();361                this.spy();362                assert.equals(this.spy.callCount, 2);363            },364            "increases call count for each call": function () {365                this.spy();366                this.spy();367                assert.equals(this.spy.callCount, 2);368                this.spy();369                assert.equals(this.spy.callCount, 3);370            }371        },372        "calledOn": {373            setUp: function () {374                this.spy = sinon.spy.create();375            },376            "is false if spy wasn't called": function () {377                assert.isFalse(this.spy.calledOn({}));378            },379            "is true if called with thisValue": function () {380                var object = {};381                this.spy.call(object);382                assert(this.spy.calledOn(object));383            },384            "browser": {385                requiresSupportFor: { "browser": typeof window !== "undefined" },386                "is true if called on object at least once": function () {387                    var object = {};388                    this.spy();389                    this.spy.call({});390                    this.spy.call(object);391                    this.spy.call(window);392                    assert(this.spy.calledOn(object));393                }394            },395            "returns false if not called on object": function () {396                var object = {};397                this.spy.call(object);398                this.spy();399                assert.isFalse(this.spy.calledOn({}));400            },401            "is true if called with matcher that returns true": function () {402                var matcher = sinon.match(function () { return true; });403                this.spy();404                assert(this.spy.calledOn(matcher));405            },406            "is false if called with matcher that returns false": function () {407                var matcher = sinon.match(function () { return false; });408                this.spy();409                assert.isFalse(this.spy.calledOn(matcher));410            },411            "invokes matcher.test with given object": function () {412                var expected = {};413                var actual;414                this.spy.call(expected);415                this.spy.calledOn(sinon.match(function (value) {416                    actual = value;417                }));418                assert.same(actual, expected);419            }420        },421        "alwaysCalledOn": {422            setUp: function () {423                this.spy = sinon.spy.create();424            },425            "is false prior to calling the spy": function () {426                assert.isFalse(this.spy.alwaysCalledOn({}));427            },428            "is true if called with thisValue once": function () {429                var object = {};430                this.spy.call(object);431                assert(this.spy.alwaysCalledOn(object));432            },433            "is true if called with thisValue many times": function () {434                var object = {};435                this.spy.call(object);436                this.spy.call(object);437                this.spy.call(object);438                this.spy.call(object);439                assert(this.spy.alwaysCalledOn(object));440            },441            "is false if called with another object atleast once": function () {442                var object = {};443                this.spy.call(object);444                this.spy.call(object);445                this.spy.call(object);446                this.spy();447                this.spy.call(object);448                assert.isFalse(this.spy.alwaysCalledOn(object));449            },450            "is false if never called with expected object": function () {451                var object = {};452                this.spy();453                this.spy();454                this.spy();455                assert.isFalse(this.spy.alwaysCalledOn(object));456            }457        },458        "calledWithNew": {459            setUp: function () {460                this.spy = sinon.spy.create();461            },462            "is false if spy wasn't called": function () {463                assert.isFalse(this.spy.calledWithNew());464            },465            "is true if called with new": function () {466                var result = new this.spy();467                assert(this.spy.calledWithNew());468            },469            "is true if called with new on custom constructor": function () {470                function MyThing() {}471                MyThing.prototype = {};472                var ns = { MyThing: MyThing };473                sinon.spy(ns, "MyThing");474                var result = new ns.MyThing();475                assert(ns.MyThing.calledWithNew());476            },477            "is false if called as function": function () {478                this.spy();479                assert.isFalse(this.spy.calledWithNew());480            },481            "browser": {482                requiresSupportFor: { "browser": typeof window !== "undefined" },483                "is true if called with new at least once": function () {484                    var object = {};485                    this.spy();486                    var a = new this.spy();487                    this.spy(object);488                    this.spy(window);489                    assert(this.spy.calledWithNew());490                }491            },492            "is true newed constructor returns object": function () {493                function MyThing() { return {}; }494                var object = { MyThing: MyThing };495                sinon.spy(object, "MyThing");496                var result = new object.MyThing;497                assert(object.MyThing.calledWithNew());498            }499        },500        "alwaysCalledWithNew": {501            setUp: function () {502                this.spy = sinon.spy.create();503            },504            "is false if spy wasn't called": function () {505                assert.isFalse(this.spy.alwaysCalledWithNew());506            },507            "is true if always called with new": function () {508                var result = new this.spy();509                var result2 = new this.spy();510                var result3 = new this.spy();511                assert(this.spy.alwaysCalledWithNew());512            },513            "is false if called as function once": function () {514                var result = new this.spy();515                var result2 = new this.spy();516                this.spy();517                assert.isFalse(this.spy.alwaysCalledWithNew());518            }519        },520        "thisValue": {521            setUp: function () {522                this.spy = sinon.spy.create();523            },524            "contains one object": function () {525                var object = {};526                this.spy.call(object);527                assert.equals(this.spy.thisValues, [object]);528            },529            "stacks up objects": function () {530                function MyConstructor() {}531                var objects = [{}, [], new MyConstructor(), { id: 243 }];532                this.spy();533                this.spy.call(objects[0]);534                this.spy.call(objects[1]);535                this.spy.call(objects[2]);536                this.spy.call(objects[3]);537                assert.equals(this.spy.thisValues, [this].concat(objects));538            }539        },540        "calledWith": spyCalledTests("calledWith"),541        "calledWithMatch": spyCalledTests("calledWithMatch"),542        "calledWithMatchSpecial": {543            setUp: function () {544                this.spy = sinon.spy.create();545            },546            "checks substring match": function () {547                this.spy("I like it");548                assert(this.spy.calledWithMatch("like"));549                assert.isFalse(this.spy.calledWithMatch("nope"));550            },551            "checks for regexp match": function () {552                this.spy("I like it");553                assert(this.spy.calledWithMatch(/[a-z ]+/i));554                assert.isFalse(this.spy.calledWithMatch(/[0-9]+/));555            },556            "checks for partial object match": function () {557                this.spy({ foo: "foo", bar: "bar" });558                assert(this.spy.calledWithMatch({ bar: "bar" }));559                assert.isFalse(this.spy.calledWithMatch({ same: "same" }));560            }561        },562        "alwaysCalledWith": spyAlwaysCalledTests("alwaysCalledWith"),563        "alwaysCalledWithMatch": spyAlwaysCalledTests("alwaysCalledWithMatch"),564        "alwaysCalledWithMatchSpecial": {565            setUp: function () {566                this.spy = sinon.spy.create();567            },568            "checks true": function () {569                this.spy(true);570                assert(this.spy.alwaysCalledWithMatch(true));571                assert.isFalse(this.spy.alwaysCalledWithMatch(false));572            },573            "checks false": function () {574                this.spy(false);575                assert(this.spy.alwaysCalledWithMatch(false));576                assert.isFalse(this.spy.alwaysCalledWithMatch(true));577            },578            "checks substring match": function () {579                this.spy("test case");580                this.spy("some test");581                this.spy("all tests");582                assert(this.spy.alwaysCalledWithMatch("test"));583                assert.isFalse(this.spy.alwaysCalledWithMatch("case"));584            },585            "checks regexp match": function () {586                this.spy("1");587                this.spy("2");588                this.spy("3");589                assert(this.spy.alwaysCalledWithMatch(/[123]/));590                assert.isFalse(this.spy.alwaysCalledWithMatch(/[12]/));591            },592            "checks partial object match": function () {593                this.spy({ a: "a", b: "b" });594                this.spy({ c: "c", b: "b" });595                this.spy({ b: "b", d: "d" });596                assert(this.spy.alwaysCalledWithMatch({ b: "b" }));597                assert.isFalse(this.spy.alwaysCalledWithMatch({ a: "a" }));598            }599        },600        "neverCalledWith": spyNeverCalledTests("neverCalledWith"),601        "neverCalledWithMatch": spyNeverCalledTests("neverCalledWithMatch"),602        "neverCalledWithMatchSpecial": {603            setUp: function () {604                this.spy = sinon.spy.create();605            },606            "checks substring match": function () {607                this.spy("a test", "b test");608                assert(this.spy.neverCalledWithMatch("a", "a"));609                assert(this.spy.neverCalledWithMatch("b", "b"));610                assert(this.spy.neverCalledWithMatch("b", "a"));611                assert.isFalse(this.spy.neverCalledWithMatch("a", "b"));612            },613            "checks regexp match": function () {614                this.spy("a test", "b test");615                assert(this.spy.neverCalledWithMatch(/a/, /a/));616                assert(this.spy.neverCalledWithMatch(/b/, /b/));617                assert(this.spy.neverCalledWithMatch(/b/, /a/));618                assert.isFalse(this.spy.neverCalledWithMatch(/a/, /b/));619            },620            "checks partial object match": function () {621                this.spy({ a: "test", b: "test" });622                assert(this.spy.neverCalledWithMatch({ a: "nope" }));623                assert(this.spy.neverCalledWithMatch({ c: "test" }));624                assert.isFalse(this.spy.neverCalledWithMatch({ b: "test" }));625            }626        },627        "args": {628            setUp: function () {629                this.spy = sinon.spy.create();630            },631            "contains real arrays": function () {632                this.spy();633                assert.isArray(this.spy.args[0]);634            },635            "contains empty array when no arguments": function () {636                this.spy();637                assert.equals(this.spy.args, [[]]);638            },639            "contains array with first call's arguments": function () {640                this.spy(1, 2, 3);641                assert.equals(this.spy.args, [[1, 2, 3]]);642            },643            "stacks up arguments in nested array": function () {644                var objects = [{}, [], { id: 324 }];645                this.spy(1, objects[0], 3);646                this.spy(1, 2, objects[1]);647                this.spy(objects[2], 2, 3);648                assert.equals(this.spy.args,649                              [[1, objects[0], 3],650                               [1, 2, objects[1]],651                               [objects[2], 2, 3]]);652            }653        },654        "calledWithExactly": {655            setUp: function () {656                this.spy = sinon.spy.create();657            },658            "returns false for partial match": function () {659                this.spy(1, 2, 3);660                assert.isFalse(this.spy.calledWithExactly(1, 2));661            },662            "returns false for missing arguments": function () {663                this.spy(1, 2, 3);664                assert.isFalse(this.spy.calledWithExactly(1, 2, 3, 4));665            },666            "returns true for exact match": function () {667                this.spy(1, 2, 3);668                assert(this.spy.calledWithExactly(1, 2, 3));669            },670            "matchs by strict comparison": function () {671                this.spy({}, []);672                assert.isFalse(this.spy.calledWithExactly({}, [], null));673            },674            "returns true for one exact match": function () {675                var object = {};676                var array = [];677                this.spy({}, []);678                this.spy(object, []);679                this.spy(object, array);680                assert(this.spy.calledWithExactly(object, array));681            }682        },683        "alwaysCalledWithExactly": {684            setUp: function () {685                this.spy = sinon.spy.create();686            },687            "returns false for partial match": function () {688                this.spy(1, 2, 3);689                assert.isFalse(this.spy.alwaysCalledWithExactly(1, 2));690            },691            "returns false for missing arguments": function () {692                this.spy(1, 2, 3);693                assert.isFalse(this.spy.alwaysCalledWithExactly(1, 2, 3, 4));694            },695            "returns true for exact match": function () {696                this.spy(1, 2, 3);697                assert(this.spy.alwaysCalledWithExactly(1, 2, 3));698            },699            "returns false for excess arguments": function () {700                this.spy({}, []);701                assert.isFalse(this.spy.alwaysCalledWithExactly({}, [], null));702            },703            "returns false for one exact match": function () {704                var object = {};705                var array = [];706                this.spy({}, []);707                this.spy(object, []);708                this.spy(object, array);709                assert(this.spy.alwaysCalledWithExactly(object, array));710            },711            "returns true for only exact matches": function () {712                var object = {};713                var array = [];714                this.spy(object, array);715                this.spy(object, array);716                this.spy(object, array);717                assert(this.spy.alwaysCalledWithExactly(object, array));718            },719            "returns false for no exact matches": function () {720                var object = {};721                var array = [];722                this.spy(object, array, null);723                this.spy(object, array, undefined);724                this.spy(object, array, "");725                assert.isFalse(this.spy.alwaysCalledWithExactly(object, array));726            }727        },728        "threw": {729            setUp: function () {730                this.spy = sinon.spy.create();731                this.spyWithTypeError = sinon.spy.create(function () {732                    throw new TypeError();733                });734                735                this.spyWithStringError = sinon.spy.create(function() {736                	throw "error";737                });738            },739            "returns exception thrown by function": function () {740                var err = new Error();741                var spy = sinon.spy.create(function () {742                    throw err;743                });744                try {745                    spy();746                } catch (e) {}747                assert(spy.threw(err));748            },749            "returns false if spy did not throw": function () {750                this.spy();751                assert.isFalse(this.spy.threw());752            },753            "returns true if spy threw": function () {754                try {755                    this.spyWithTypeError();756                } catch (e) {}757                assert(this.spyWithTypeError.threw());758            },759            "returns true if string type matches": function () {760                try {761                    this.spyWithTypeError();762                } catch (e) {}763                assert(this.spyWithTypeError.threw("TypeError"));764            },765            "returns false if string did not match": function () {766                try {767                    this.spyWithTypeError();768                } catch (e) {}769                assert.isFalse(this.spyWithTypeError.threw("Error"));770            },771            "returns false if spy did not throw specified error": function () {772                this.spy();773                assert.isFalse(this.spy.threw("Error"));774            },775            776            "returns true if string matches": function () {777            	try {778            		this.spyWithStringError();779            	} catch (e) {}780            	781            	assert(this.spyWithStringError.threw("error"));782            },783            784            "returns false if strings do not match": function() {785            	try {786            		this.spyWithStringError();787            	} catch (e) {}788            	789            	assert.isFalse(this.spyWithStringError.threw("not the error"));790            }791        },792        "alwaysThrew": {793            setUp: function () {794                this.spy = sinon.spy.create();795                this.spyWithTypeError = sinon.spy.create(function () {796                    throw new TypeError();797                });798            },799            "returns true when spy threw": function () {800                var err = new Error();801                var spy = sinon.spy.create(function () {802                    throw err;803                });804                try {805                    spy();806                } catch (e) {}807                assert(spy.alwaysThrew(err));808            },809            "returns false if spy did not throw": function () {810                this.spy();811                assert.isFalse(this.spy.alwaysThrew());812            },813            "returns true if spy threw": function () {814                try {815                    this.spyWithTypeError();816                } catch (e) {}817                assert(this.spyWithTypeError.alwaysThrew());818            },819            "returns true if string type matches": function () {820                try {821                    this.spyWithTypeError();822                } catch (e) {}823                assert(this.spyWithTypeError.alwaysThrew("TypeError"));824            },825            "returns false if string did not match": function () {826                try {827                    this.spyWithTypeError();828                } catch (e) {}829                assert.isFalse(this.spyWithTypeError.alwaysThrew("Error"));830            },831            "returns false if spy did not throw specified error": function () {832                this.spy();833                assert.isFalse(this.spy.alwaysThrew("Error"));834            },835            "returns false if some calls did not throw": function () {836                var spy = sinon.stub.create(function () {837                    if (spy.callCount === 0) {838                        throw new Error();839                    }840                });841                try {842                    this.spy();843                } catch (e) {}844                this.spy();845                assert.isFalse(this.spy.alwaysThrew());846            },847            "returns true if all calls threw": function () {848                try {849                    this.spyWithTypeError();850                } catch (e1) {}851                try {852                    this.spyWithTypeError();853                } catch (e2) {}854                assert(this.spyWithTypeError.alwaysThrew());855            },856            "returns true if all calls threw same type": function () {857                try {858                    this.spyWithTypeError();859                } catch (e1) {}860                try {861                    this.spyWithTypeError();862                } catch (e2) {}863                assert(this.spyWithTypeError.alwaysThrew("TypeError"));864            }865        },866        "exceptions": {867            setUp: function () {868                this.spy = sinon.spy.create();869                var error = this.error = {};870                this.spyWithTypeError = sinon.spy.create(function () {871                    throw error;872                });873            },874            "contains exception thrown by function": function () {875                try {876                    this.spyWithTypeError();877                } catch (e) {}878                assert.equals(this.spyWithTypeError.exceptions, [this.error]);879            },880            "contains undefined entry when function did not throw": function () {881                this.spy();882                assert.equals(this.spy.exceptions.length, 1);883                refute.defined(this.spy.exceptions[0]);884            },885            "stacks up exceptions and undefined": function () {886                var calls = 0;887                var err = this.error;888                var spy = sinon.spy.create(function () {889                    calls += 1;890                    if (calls % 2 === 0) {891                        throw err;892                    }893                });894                spy();895                try {896                    spy();897                } catch (e1) {}898                spy();899                try {900                    spy();901                } catch (e2) {}902                spy();903                assert.equals(spy.exceptions.length, 5);904                refute.defined(spy.exceptions[0]);905                assert.equals(spy.exceptions[1], err);906                refute.defined(spy.exceptions[2]);907                assert.equals(spy.exceptions[3], err);908                refute.defined(spy.exceptions[4]);909            }910        },911        "returned": {912            "returns true when no argument": function () {913                var spy = sinon.spy.create();914                spy();915                assert(spy.returned());916            },917            "returns true for undefined when no explicit return": function () {918                var spy = sinon.spy.create();919                spy();920                assert(spy.returned(undefined));921            },922            "returns true when returned value once": function () {923                var values = [{}, 2, "hey", function () {}];924                var spy = sinon.spy.create(function () {925                    return values[spy.callCount];926                });927                spy();928                spy();929                spy();930                spy();931                assert(spy.returned(values[3]));932            },933            "returns false when value is never returned": function () {934                var values = [{}, 2, "hey", function () {}];935                var spy = sinon.spy.create(function () {936                    return values[spy.callCount];937                });938                spy();939                spy();940                spy();941                spy();942                assert.isFalse(spy.returned({ id: 42 }));943            },944            "returns true when value is returned several times": function () {945                var object = { id: 42 };946                var spy = sinon.spy.create(function () {947                    return object;948                });949                spy();950                spy();951                spy();952                assert(spy.returned(object));953            },954            "compares values deeply": function () {955                var object = { deep: { id: 42 } };956                var spy = sinon.spy.create(function () {957                    return object;958                });959                spy();960                assert(spy.returned({ deep: { id: 42 } }));961            },962            "compares values strictly using match.same": function () {963                var object = { id: 42 };964                var spy = sinon.spy.create(function () {965                    return object;966                });967                spy();968                assert.isFalse(spy.returned(sinon.match.same({ id: 42 })));969                assert(spy.returned(sinon.match.same(object)));970            }971        },972        "returnValues": {973            "contains undefined when function does not return explicitly": function () {974                var spy = sinon.spy.create();975                spy();976                assert.equals(spy.returnValues.length, 1);977                refute.defined(spy.returnValues[0]);978            },979            "contains return value": function () {980                var object = { id: 42 };981                var spy = sinon.spy.create(function () {982                    return object;983                });984                spy();985                assert.equals(spy.returnValues, [object]);986            },987            "contains undefined when function throws": function () {988                var spy = sinon.spy.create(function () {989                    throw new Error();990                });991                try {992                    spy();993                } catch (e) {994                }995                assert.equals(spy.returnValues.length, 1);996                refute.defined(spy.returnValues[0]);997            },998            "stacks up return values": function () {999                var calls = 0;1000                var spy = sinon.spy.create(function () {1001                    calls += 1;1002                    if (calls % 2 === 0) {1003                        return calls;1004                    }1005                });1006                spy();1007                spy();1008                spy();1009                spy();1010                spy();1011                assert.equals(spy.returnValues.length, 5);1012                refute.defined(spy.returnValues[0]);1013                assert.equals(spy.returnValues[1], 2);1014                refute.defined(spy.returnValues[2]);1015                assert.equals(spy.returnValues[3], 4);1016                refute.defined(spy.returnValues[4]);1017            }1018        },1019        "calledBefore": {1020            setUp: function () {1021                this.spy1 = sinon.spy();1022                this.spy2 = sinon.spy();1023            },1024            "is function": function () {1025                assert.isFunction(this.spy1.calledBefore);1026            },1027            "returns true if first call to A was before first to B": function () {1028                this.spy1();1029                this.spy2();1030                assert(this.spy1.calledBefore(this.spy2));1031            },1032            "compares call order of calls directly": function () {1033                this.spy1();1034                this.spy2();1035                assert(this.spy1.getCall(0).calledBefore(this.spy2.getCall(0)));1036            },1037            "returns false if not called": function () {1038                this.spy2();1039                assert.isFalse(this.spy1.calledBefore(this.spy2));1040            },1041            "returns true if other not called": function () {1042                this.spy1();1043                assert(this.spy1.calledBefore(this.spy2));1044            },1045            "returns false if other called first": function () {1046                this.spy2();1047                this.spy1();1048                this.spy2();1049                assert(this.spy1.calledBefore(this.spy2));1050            }1051        },1052        "calledAfter": {1053            setUp: function () {1054                this.spy1 = sinon.spy();1055                this.spy2 = sinon.spy();1056            },1057            "is function": function () {1058                assert.isFunction(this.spy1.calledAfter);1059            },1060            "returns true if first call to A was after first to B": function () {1061                this.spy2();1062                this.spy1();1063                assert(this.spy1.calledAfter(this.spy2));1064            },1065            "compares calls directly": function () {1066                this.spy2();1067                this.spy1();1068                assert(this.spy1.getCall(0).calledAfter(this.spy2.getCall(0)));1069            },1070            "returns false if not called": function () {1071                this.spy2();1072                assert.isFalse(this.spy1.calledAfter(this.spy2));1073            },1074            "returns false if other not called": function () {1075                this.spy1();1076                assert.isFalse(this.spy1.calledAfter(this.spy2));1077            },1078            "returns false if other called last": function () {1079                this.spy2();1080                this.spy1();1081                this.spy2();1082                assert.isFalse(this.spy1.calledAfter(this.spy2));1083            }1084        },1085        "firstCall": {1086            "is undefined by default": function () {1087                var spy = sinon.spy();1088                assert.isNull(spy.firstCall);1089            },1090            "is equal to getCall(0) result after first call": function () {1091                var spy = sinon.spy();1092                spy();1093                var call0 = spy.getCall(0);1094                assert.equals(spy.firstCall.callId, call0.callId);1095                assert.same(spy.firstCall.spy, call0.spy);1096            }1097        },1098        "secondCall": {1099            "is null by default": function () {1100                var spy = sinon.spy();1101                assert.isNull(spy.secondCall);1102            },1103            "stills be null after first call": function () {1104                var spy = sinon.spy();1105                spy();1106                assert.isNull(spy.secondCall);1107            },1108            "is equal to getCall(1) result after second call": function () {1109                var spy = sinon.spy();1110                spy();1111                spy();1112                var call1 = spy.getCall(1);1113                assert.equals(spy.secondCall.callId, call1.callId);1114                assert.same(spy.secondCall.spy, call1.spy);1115            }1116        },1117        "thirdCall": {1118            "is undefined by default": function () {1119                var spy = sinon.spy();1120                assert.isNull(spy.thirdCall);1121            },1122            "stills be undefined after second call": function () {1123                var spy = sinon.spy();1124                spy();1125                spy();1126                assert.isNull(spy.thirdCall);1127            },1128            "is equal to getCall(1) result after second call": function () {1129                var spy = sinon.spy();1130                spy();1131                spy();1132                spy();1133                var call2 = spy.getCall(2);1134                assert.equals(spy.thirdCall.callId, call2.callId);1135                assert.same(spy.thirdCall.spy, call2.spy);1136            }1137        },1138        "lastCall": {1139            "is undefined by default": function () {1140                var spy = sinon.spy();1141                assert.isNull(spy.lastCall);1142            },1143            "is same as firstCall after first call": function () {1144                var spy = sinon.spy();1145                spy();1146                assert.same(spy.lastCall.callId, spy.firstCall.callId);1147                assert.same(spy.lastCall.spy, spy.firstCall.spy);1148            },1149            "is same as secondCall after second call": function () {1150                var spy = sinon.spy();1151                spy();1152                spy();1153                assert.same(spy.lastCall.callId, spy.secondCall.callId);1154                assert.same(spy.lastCall.spy, spy.secondCall.spy);1155            },1156            "is same as thirdCall after third call": function () {1157                var spy = sinon.spy();1158                spy();1159                spy();1160                spy();1161                assert.same(spy.lastCall.callId, spy.thirdCall.callId);1162                assert.same(spy.lastCall.spy, spy.thirdCall.spy);1163            },1164            "is equal to getCall(3) result after fourth call": function () {1165                var spy = sinon.spy();1166                spy();1167                spy();1168                spy();1169                spy();1170                var call3 = spy.getCall(3);1171                assert.equals(spy.lastCall.callId, call3.callId);1172                assert.same(spy.lastCall.spy, call3.spy);1173            },1174            "is equal to getCall(4) result after fifth call": function () {1175                var spy = sinon.spy();1176                spy();1177                spy();1178                spy();1179                spy();1180                spy();1181                var call4 = spy.getCall(4);1182                assert.equals(spy.lastCall.callId, call4.callId);1183                assert.same(spy.lastCall.spy, call4.spy);1184            }1185        },1186        "callArg": {1187            "is function": function () {1188                var spy = sinon.spy();1189                assert.isFunction(spy.callArg);1190            },1191            "invokes argument at index for all calls": function () {1192                var spy = sinon.spy();1193                var callback = sinon.spy();1194                spy(1, 2, callback);1195                spy(3, 4, callback);1196                spy.callArg(2);1197                assert(callback.calledTwice);1198                assert(callback.alwaysCalledWith());1199            },1200            "throws if argument at index is not a function": function () {1201                var spy = sinon.spy();1202                spy();1203                assert.exception(function () {1204                    spy.callArg(1);1205                }, "TypeError");1206            },1207            "throws if spy was not yet invoked": function () {1208                var spy = sinon.spy();1209                try {1210                    spy.callArg(0);1211                    throw new Error();1212                } catch (e) {1213                    assert.equals(e.message, "spy cannot call arg since it was not yet invoked.");1214                }1215            },1216            "includes spy name in error message": function () {1217                var api = { someMethod: function () {} };1218                var spy = sinon.spy(api, "someMethod");1219                try {1220                    spy.callArg(0);1221                    throw new Error();1222                } catch (e) {1223                    assert.equals(e.message, "someMethod cannot call arg since it was not yet invoked.");1224                }1225            },1226            "throws if index is not a number": function () {1227                var spy = sinon.spy();1228                spy();1229                assert.exception(function () {1230                    spy.callArg("");1231                }, "TypeError");1232            },1233            "passs additional arguments": function () {1234                var spy = sinon.spy();1235                var callback = sinon.spy();1236                var array = [];1237                var object = {};1238                spy(callback);1239                spy.callArg(0, "abc", 123, array, object);1240                assert(callback.calledWith("abc", 123, array, object));1241            }1242        },1243        "callArgOn": {1244            "is function": function () {1245                var spy = sinon.spy();1246                assert.isFunction(spy.callArgOn);1247            },1248            "invokes argument at index for all calls": function () {1249                var spy = sinon.spy();1250                var callback = sinon.spy();1251                var thisObj = { name1: "value1", name2: "value2" };1252                spy(1, 2, callback);1253                spy(3, 4, callback);1254                spy.callArgOn(2, thisObj);1255                assert(callback.calledTwice);1256                assert(callback.alwaysCalledWith());1257                assert(callback.alwaysCalledOn(thisObj));1258            },1259            "throws if argument at index is not a function": function () {1260                var spy = sinon.spy();1261                var thisObj = { name1: "value1", name2: "value2" };1262                spy();1263                assert.exception(function () {1264                    spy.callArgOn(1, thisObj);1265                }, "TypeError");1266            },1267            "throws if spy was not yet invoked": function () {1268                var spy = sinon.spy();1269                var thisObj = { name1: "value1", name2: "value2" };1270                try {1271                    spy.callArgOn(0, thisObj);1272                    throw new Error();1273                } catch (e) {1274                    assert.equals(e.message, "spy cannot call arg since it was not yet invoked.");1275                }1276            },1277            "includes spy name in error message": function () {1278                var api = { someMethod: function () {} };1279                var spy = sinon.spy(api, "someMethod");1280                var thisObj = { name1: "value1", name2: "value2" };1281                try {1282                    spy.callArgOn(0, thisObj);1283                    throw new Error();1284                } catch (e) {1285                    assert.equals(e.message, "someMethod cannot call arg since it was not yet invoked.");1286                }1287            },1288            "throws if index is not a number": function () {1289                var spy = sinon.spy();1290                var thisObj = { name1: "value1", name2: "value2" };1291                spy();1292                assert.exception(function () {1293                    spy.callArg("", thisObj);1294                }, "TypeError");1295            },1296            "pass additional arguments": function () {1297                var spy = sinon.spy();1298                var callback = sinon.spy();1299                var array = [];1300                var object = {};1301                var thisObj = { name1: "value1", name2: "value2" };1302                spy(callback);1303                spy.callArgOn(0, thisObj, "abc", 123, array, object);1304                assert(callback.calledWith("abc", 123, array, object));1305                assert(callback.calledOn(thisObj));1306            }1307        },1308        "callArgWith": {1309            "is alias for callArg": function () {1310                var spy = sinon.spy();1311                assert.same(spy.callArgWith, spy.callArg);1312            }1313        },1314        "callArgOnWith": {1315            "is alias for callArgOn": function () {1316                var spy = sinon.spy();1317                assert.same(spy.callArgOnWith, spy.callArgOn);1318            }1319        },1320        "yield": {1321            "is function": function () {1322                var spy = sinon.spy();1323                assert.isFunction(spy.yield);1324            },1325            "invokes first function arg for all calls": function () {1326                var spy = sinon.spy();1327                var callback = sinon.spy();1328                spy(1, 2, callback);1329                spy(3, 4, callback);1330                spy.yield();1331                assert(callback.calledTwice);1332                assert(callback.alwaysCalledWith());1333            },1334            "throws if spy was not yet invoked": function () {1335                var spy = sinon.spy();1336                try {1337                    spy.yield();1338                    throw new Error();1339                } catch (e) {1340                    assert.equals(e.message, "spy cannot yield since it was not yet invoked.");1341                }1342            },1343            "includes spy name in error message": function () {1344                var api = { someMethod: function () {} };1345                var spy = sinon.spy(api, "someMethod");1346                try {1347                    spy.yield();1348                    throw new Error();1349                } catch (e) {1350                    assert.equals(e.message, "someMethod cannot yield since it was not yet invoked.");1351                }1352            },1353            "passs additional arguments": function () {1354                var spy = sinon.spy();1355                var callback = sinon.spy();1356                var array = [];1357                var object = {};1358                spy(callback);1359                spy.yield("abc", 123, array, object);1360                assert(callback.calledWith("abc", 123, array, object));1361            }1362        },1363        "invokeCallback": {1364            "is alias for yield": function () {1365                var spy = sinon.spy();1366                assert.same(spy.invokeCallback, spy.yield);1367            }1368        },1369        "yieldOn": {1370            "is function": function () {1371                var spy = sinon.spy();1372                assert.isFunction(spy.yieldOn);1373            },1374            "invokes first function arg for all calls": function () {1375                var spy = sinon.spy();1376                var callback = sinon.spy();1377                var thisObj = { name1: "value1", name2: "value2" };1378                spy(1, 2, callback);1379                spy(3, 4, callback);1380                spy.yieldOn(thisObj);1381                assert(callback.calledTwice);1382                assert(callback.alwaysCalledWith());1383                assert(callback.alwaysCalledOn(thisObj));1384            },1385            "throws if spy was not yet invoked": function () {1386                var spy = sinon.spy();1387                var thisObj = { name1: "value1", name2: "value2" };1388                try {1389                    spy.yieldOn(thisObj);1390                    throw new Error();1391                } catch (e) {1392                    assert.equals(e.message, "spy cannot yield since it was not yet invoked.");1393                }1394            },1395            "includes spy name in error message": function () {1396                var api = { someMethod: function () {} };1397                var spy = sinon.spy(api, "someMethod");1398                var thisObj = { name1: "value1", name2: "value2" };1399                try {1400                    spy.yieldOn(thisObj);1401                    throw new Error();1402                } catch (e) {1403                    assert.equals(e.message, "someMethod cannot yield since it was not yet invoked.");1404                }1405            },1406            "pass additional arguments": function () {1407                var spy = sinon.spy();1408                var callback = sinon.spy();1409                var array = [];1410                var object = {};1411                var thisObj = { name1: "value1", name2: "value2" };1412                spy(callback);1413                spy.yieldOn(thisObj, "abc", 123, array, object);1414                assert(callback.calledWith("abc", 123, array, object));1415                assert(callback.calledOn(thisObj));1416            }1417        },1418        "yieldTo": {1419            "is function": function () {1420                var spy = sinon.spy();1421                assert.isFunction(spy.yieldTo);1422            },1423            "invokes first function arg for all calls": function () {1424                var spy = sinon.spy();1425                var callback = sinon.spy();1426                spy(1, 2, { success: callback });1427                spy(3, 4, { success: callback });1428                spy.yieldTo("success");1429                assert(callback.calledTwice);1430                assert(callback.alwaysCalledWith());1431            },1432            "throws if spy was not yet invoked": function () {1433                var spy = sinon.spy();1434                try {1435                    spy.yieldTo("success");1436                    throw new Error();1437                } catch (e) {1438                    assert.equals(e.message, "spy cannot yield to 'success' since it was not yet invoked.");1439                }1440            },1441            "includes spy name in error message": function () {1442                var api = { someMethod: function () {} };1443                var spy = sinon.spy(api, "someMethod");1444                try {1445                    spy.yieldTo("success");1446                    throw new Error();1447                } catch (e) {1448                    assert.equals(e.message, "someMethod cannot yield to 'success' since it was not yet invoked.");1449                }1450            },1451        "passs additional arguments": function () {1452                var spy = sinon.spy();1453                var callback = sinon.spy();1454                var array = [];1455                var object = {};1456                spy({ test: callback });1457                spy.yieldTo("test", "abc", 123, array, object);1458                assert(callback.calledWith("abc", 123, array, object));1459            }1460        },1461        "yieldToOn": {1462            "is function": function () {1463                var spy = sinon.spy();1464                assert.isFunction(spy.yieldToOn);1465            },1466            "invokes first function arg for all calls": function () {1467                var spy = sinon.spy();1468                var callback = sinon.spy();1469                var thisObj = { name1: "value1", name2: "value2" };1470                spy(1, 2, { success: callback });1471                spy(3, 4, { success: callback });1472                spy.yieldToOn("success", thisObj);1473                assert(callback.calledTwice);1474                assert(callback.alwaysCalledWith());1475                assert(callback.alwaysCalledOn(thisObj));1476            },1477            "throws if spy was not yet invoked": function () {1478                var spy = sinon.spy();1479                var thisObj = { name1: "value1", name2: "value2" };1480                try {1481                    spy.yieldToOn("success", thisObj);1482                    throw new Error();1483                } catch (e) {1484                    assert.equals(e.message, "spy cannot yield to 'success' since it was not yet invoked.");1485                }1486            },1487            "includes spy name in error message": function () {1488                var api = { someMethod: function () {} };1489                var spy = sinon.spy(api, "someMethod");1490                var thisObj = { name1: "value1", name2: "value2" };1491                try {1492                    spy.yieldToOn("success", thisObj);1493                    throw new Error();1494                } catch (e) {1495                    assert.equals(e.message, "someMethod cannot yield to 'success' since it was not yet invoked.");1496                }1497            },1498            "pass additional arguments": function () {1499                var spy = sinon.spy();1500                var callback = sinon.spy();1501                var array = [];1502                var object = {};1503                var thisObj = { name1: "value1", name2: "value2" };1504                spy({ test: callback });1505                spy.yieldToOn("test", thisObj, "abc", 123, array, object);1506                assert(callback.calledWith("abc", 123, array, object));1507                assert(callback.calledOn(thisObj));1508            }1509        }1510    });...

Full Screen

Full Screen

asyncBehaviors.js

Source:asyncBehaviors.js Github

copy

Full Screen

1describe("Throttled observables", function() {2    beforeEach(function() { waits(1); }); // Workaround for spurious timing-related failures on IE8 (issue #736)3    it("Should notify subscribers asynchronously after writes stop for the specified timeout duration", function() {4        var observable = ko.observable('A').extend({ throttle: 100 });5        var notifiedValues = [];6        observable.subscribe(function(value) {7            notifiedValues.push(value);8        });9        runs(function() {10            // Mutate a few times11            observable('B');12            observable('C');13            observable('D');14            expect(notifiedValues.length).toEqual(0); // Should not notify synchronously15        });16        // Wait17        waits(10);18        runs(function() {19            // Mutate more20            observable('E');21            observable('F');22            expect(notifiedValues.length).toEqual(0); // Should not notify until end of throttle timeout23        });24        // Wait until after timeout25        waitsFor(function() {26            return notifiedValues.length > 0;27        }, 300);28        runs(function() {29            expect(notifiedValues.length).toEqual(1);30            expect(notifiedValues[0]).toEqual("F");31        });32    });33});34describe("Throttled dependent observables", function() {35    beforeEach(function() { waits(1); }); // Workaround for spurious timing-related failures on IE8 (issue #736)36    it("Should notify subscribers asynchronously after dependencies stop updating for the specified timeout duration", function() {37        var underlying = ko.observable();38        var asyncDepObs = ko.dependentObservable(function() {39            return underlying();40        }).extend({ throttle: 100 });41        var notifiedValues = [];42        asyncDepObs.subscribe(function(value) {43            notifiedValues.push(value);44        });45        // Check initial state46        expect(asyncDepObs()).toBeUndefined();47        runs(function() {48            // Mutate49            underlying('New value');50            expect(asyncDepObs()).toBeUndefined(); // Should not update synchronously51            expect(notifiedValues.length).toEqual(0);52        });53        // Still shouldn't have evaluated54        waits(10);55        runs(function() {56            expect(asyncDepObs()).toBeUndefined(); // Should not update until throttle timeout57            expect(notifiedValues.length).toEqual(0);58        });59        // Now wait for throttle timeout60        waitsFor(function() {61            return notifiedValues.length > 0;62        }, 300);63        runs(function() {64            expect(asyncDepObs()).toEqual('New value');65            expect(notifiedValues.length).toEqual(1);66            expect(notifiedValues[0]).toEqual('New value');67        });68    });69    it("Should run evaluator only once when dependencies stop updating for the specified timeout duration", function() {70        var evaluationCount = 0;71        var someDependency = ko.observable();72        var asyncDepObs = ko.dependentObservable(function() {73            evaluationCount++;74            return someDependency();75        }).extend({ throttle: 100 });76        runs(function() {77            // Mutate a few times synchronously78            expect(evaluationCount).toEqual(1); // Evaluates synchronously when first created, like all dependent observables79            someDependency("A");80            someDependency("B");81            someDependency("C");82            expect(evaluationCount).toEqual(1); // Should not re-evaluate synchronously when dependencies update83        });84        // Also mutate async85        waits(10);86        runs(function() {87            someDependency("D");88            expect(evaluationCount).toEqual(1);89        });90        // Now wait for throttle timeout91        waitsFor(function() {92            return evaluationCount > 1;93        }, 300);94        runs(function() {95            expect(evaluationCount).toEqual(2); // Finally, it's evaluated96            expect(asyncDepObs()).toEqual("D");97        });98    });99});100describe('Rate-limited', function() {101    beforeEach(function() {102        jasmine.Clock.useMock();103    });104    describe('Subscribable', function() {105        it('Should delay change notifications', function() {106            var subscribable = new ko.subscribable().extend({rateLimit:500});107            var notifySpy = jasmine.createSpy('notifySpy');108            subscribable.subscribe(notifySpy);109            subscribable.subscribe(notifySpy, null, 'custom');110            // "change" notification is delayed111            subscribable.notifySubscribers('a', "change");112            expect(notifySpy).not.toHaveBeenCalled();113            // Default notification is delayed114            subscribable.notifySubscribers('b');115            expect(notifySpy).not.toHaveBeenCalled();116            // Other notifications happen immediately117            subscribable.notifySubscribers('c', "custom");118            expect(notifySpy).toHaveBeenCalledWith('c');119            // Advance clock; Change notification happens now using the latest value notified120            notifySpy.reset();121            jasmine.Clock.tick(500);122            expect(notifySpy).toHaveBeenCalledWith('b');123        });124        it('Should notify every timeout interval using notifyAtFixedRate method ', function() {125            var subscribable = new ko.subscribable().extend({rateLimit:{method:'notifyAtFixedRate', timeout:50}});126            var notifySpy = jasmine.createSpy('notifySpy');127            subscribable.subscribe(notifySpy);128            // Push 10 changes every 25 ms129            for (var i = 0; i < 10; ++i) {130                subscribable.notifySubscribers(i+1);131                jasmine.Clock.tick(25);132            }133            // Notification happens every 50 ms, so every other number is notified134            expect(notifySpy.calls.length).toBe(5);135            expect(notifySpy.argsForCall).toEqual([ [2], [4], [6], [8], [10] ]);136            // No more notifications happen137            notifySpy.reset();138            jasmine.Clock.tick(50);139            expect(notifySpy).not.toHaveBeenCalled();140        });141        it('Should notify after nothing happens for the timeout period using notifyWhenChangesStop method', function() {142            var subscribable = new ko.subscribable().extend({rateLimit:{method:'notifyWhenChangesStop', timeout:50}});143            var notifySpy = jasmine.createSpy('notifySpy');144            subscribable.subscribe(notifySpy);145            // Push 10 changes every 25 ms146            for (var i = 0; i < 10; ++i) {147                subscribable.notifySubscribers(i+1);148                jasmine.Clock.tick(25);149            }150            // No notifications happen yet151            expect(notifySpy).not.toHaveBeenCalled();152            // Notification happens after the timeout period153            jasmine.Clock.tick(50);154            expect(notifySpy.calls.length).toBe(1);155            expect(notifySpy).toHaveBeenCalledWith(10);156        });157        it('Should use latest settings when applied multiple times', function() {158            var subscribable = new ko.subscribable().extend({rateLimit:250}).extend({rateLimit:500});159            var notifySpy = jasmine.createSpy('notifySpy');160            subscribable.subscribe(notifySpy);161            subscribable.notifySubscribers('a');162            jasmine.Clock.tick(250);163            expect(notifySpy).not.toHaveBeenCalled();164            jasmine.Clock.tick(250);165            expect(notifySpy).toHaveBeenCalledWith('a');166        });167        it('Uses latest settings for future notification and previous settings for pending notificaiton', function() {168            // This test describes the current behavior for the given scenario but is not a contract for that169            // behavior, which could change in the future if convenient.170            var subscribable = new ko.subscribable().extend({rateLimit:250});171            var notifySpy = jasmine.createSpy('notifySpy');172            subscribable.subscribe(notifySpy);173            subscribable.notifySubscribers('a');  // Pending notificaiton174            // Apply new setting and schedule new notification175            subscribable = subscribable.extend({rateLimit:500});176            subscribable.notifySubscribers('b');177            // First notification happens using original settings178            jasmine.Clock.tick(250);179            expect(notifySpy).toHaveBeenCalledWith('a');180            // Second notification happends using later settings181            notifySpy.reset();182            jasmine.Clock.tick(250);183            expect(notifySpy).toHaveBeenCalledWith('b');184        });185    });186    describe('Observable', function() {187        it('Should delay change notifications', function() {188            var observable = ko.observable().extend({rateLimit:500});189            var notifySpy = jasmine.createSpy('notifySpy');190            observable.subscribe(notifySpy);191            var beforeChangeSpy = jasmine.createSpy('beforeChangeSpy')192                .andCallFake(function(value) {expect(observable()).toBe(value); });193            observable.subscribe(beforeChangeSpy, null, 'beforeChange');194            // Observable is changed, but notification is delayed195            observable('a');196            expect(observable()).toEqual('a');197            expect(notifySpy).not.toHaveBeenCalled();198            expect(beforeChangeSpy).toHaveBeenCalledWith(undefined);    // beforeChange notification happens right away199            // Second change notification is also delayed200            observable('b');201            expect(notifySpy).not.toHaveBeenCalled();202            // Advance clock; Change notification happens now using the latest value notified203            jasmine.Clock.tick(500);204            expect(notifySpy).toHaveBeenCalledWith('b');205            expect(beforeChangeSpy.calls.length).toBe(1);   // Only one beforeChange notification206        });207        it('Should suppress change notification when value is changed/reverted', function() {208            var observable = ko.observable('original').extend({rateLimit:500});209            var notifySpy = jasmine.createSpy('notifySpy');210            observable.subscribe(notifySpy);211            var beforeChangeSpy = jasmine.createSpy('beforeChangeSpy');212            observable.subscribe(beforeChangeSpy, null, 'beforeChange');213            observable('new');                      // change value214            expect(observable()).toEqual('new');    // access observable to make sure it really has the changed value215            observable('original');                 // but then change it back216            expect(notifySpy).not.toHaveBeenCalled();217            jasmine.Clock.tick(500);218            expect(notifySpy).not.toHaveBeenCalled();219            // Check that value is correct and notification hasn't happened220            expect(observable()).toEqual('original');221            expect(notifySpy).not.toHaveBeenCalled();222            // Changing observable to a new value still works as expected223            observable('new');224            jasmine.Clock.tick(500);225            expect(notifySpy).toHaveBeenCalledWith('new');226            expect(beforeChangeSpy).toHaveBeenCalledWith('original');227            expect(beforeChangeSpy).not.toHaveBeenCalledWith('new');228        });229        it('Should support notifications from nested update', function() {230            var observable = ko.observable('a').extend({rateLimit:500});231            var notifySpy = jasmine.createSpy('notifySpy');232            observable.subscribe(notifySpy);233            // Create a one-time subscription that will modify the observable234            var updateSub = observable.subscribe(function() {235                updateSub.dispose();236                observable('z');237            });238            observable('b');239            expect(notifySpy).not.toHaveBeenCalled();240            expect(observable()).toEqual('b');241            notifySpy.reset();242            jasmine.Clock.tick(500);243            expect(notifySpy).toHaveBeenCalledWith('b');244            expect(observable()).toEqual('z');245            notifySpy.reset();246            jasmine.Clock.tick(500);247            expect(notifySpy).toHaveBeenCalledWith('z');248        });249        it('Should suppress notifications when value is changed/reverted from nested update', function() {250            var observable = ko.observable('a').extend({rateLimit:500});251            var notifySpy = jasmine.createSpy('notifySpy');252            observable.subscribe(notifySpy);253            // Create a one-time subscription that will modify the observable and then revert the change254            var updateSub = observable.subscribe(function(newValue) {255                updateSub.dispose();256                observable('z');257                observable(newValue);258            });259            observable('b');260            expect(notifySpy).not.toHaveBeenCalled();261            expect(observable()).toEqual('b');262            notifySpy.reset();263            jasmine.Clock.tick(500);264            expect(notifySpy).toHaveBeenCalledWith('b');265            expect(observable()).toEqual('b');266            notifySpy.reset();267            jasmine.Clock.tick(500);268            expect(notifySpy).not.toHaveBeenCalled();269        });270        it('Should delay update of dependent computed observable', function() {271            var observable = ko.observable().extend({rateLimit:500});272            var computed = ko.computed(observable);273            // Check initial value274            expect(computed()).toBeUndefined();275            // Observable is changed, but computed is not276            observable('a');277            expect(observable()).toEqual('a');278            expect(computed()).toBeUndefined();279            // Second change also280            observable('b');281            expect(computed()).toBeUndefined();282            // Advance clock; Change notification happens now using the latest value notified283            jasmine.Clock.tick(500);284            expect(computed()).toEqual('b');285        });286        it('Should delay update of dependent pure computed observable', function() {287            var observable = ko.observable().extend({rateLimit:500});288            var computed = ko.pureComputed(observable);289            // Check initial value290            expect(computed()).toBeUndefined();291            // Observable is changed, but computed is not292            observable('a');293            expect(observable()).toEqual('a');294            expect(computed()).toBeUndefined();295            // Second change also296            observable('b');297            expect(computed()).toBeUndefined();298            // Advance clock; Change notification happens now using the latest value notified299            jasmine.Clock.tick(500);300            expect(computed()).toEqual('b');301        });302    });303    describe('Observable Array change tracking', function() {304        it('Should provide correct changelist when multiple updates are merged into one notification', function() {305            var myArray = ko.observableArray(['Alpha', 'Beta']).extend({rateLimit:1}),306                changelist;307            myArray.subscribe(function(changes) {308                changelist = changes;309            }, null, 'arrayChange');310            myArray.push('Gamma');311            myArray.push('Delta');312            jasmine.Clock.tick(10);313            expect(changelist).toEqual([314                { status : 'added', value : 'Gamma', index : 2 },315                { status : 'added', value : 'Delta', index : 3 }316            ]);317            changelist = undefined;318            myArray.shift();319            myArray.shift();320            jasmine.Clock.tick(10);321            expect(changelist).toEqual([322                { status : 'deleted', value : 'Alpha', index : 0 },323                { status : 'deleted', value : 'Beta', index : 1 }324            ]);325            changelist = undefined;326            myArray.push('Epsilon');327            myArray.pop();328            jasmine.Clock.tick(10);329            expect(changelist).toEqual(undefined);330        });331    });332    describe('Computed Observable', function() {333        it('Should delay running evaluator where there are no subscribers', function() {334            var observable = ko.observable();335            var evalSpy = jasmine.createSpy('evalSpy');336            var computed = ko.computed(function () { evalSpy(observable()); return observable(); }).extend({rateLimit:500});337            // Observable is changed, but evaluation is delayed338            evalSpy.reset();339            observable('a');340            observable('b');341            expect(evalSpy).not.toHaveBeenCalled();342            // Advance clock; Change notification happens now using the latest value notified343            evalSpy.reset();344            jasmine.Clock.tick(500);345            expect(evalSpy).toHaveBeenCalledWith('b');346        });347        it('Should delay change notifications and evaluation', function() {348            var observable = ko.observable();349            var evalSpy = jasmine.createSpy('evalSpy');350            var computed = ko.computed(function () { evalSpy(observable()); return observable(); }).extend({rateLimit:500});351            var notifySpy = jasmine.createSpy('notifySpy');352            computed.subscribe(notifySpy);353            var beforeChangeSpy = jasmine.createSpy('beforeChangeSpy')354                .andCallFake(function(value) {expect(computed()).toBe(value); });355            computed.subscribe(beforeChangeSpy, null, 'beforeChange');356            // Observable is changed, but notification is delayed357            evalSpy.reset();358            observable('a');359            expect(evalSpy).not.toHaveBeenCalled();360            expect(computed()).toEqual('a');361            expect(evalSpy).toHaveBeenCalledWith('a');      // evaluation happens when computed is accessed362            expect(notifySpy).not.toHaveBeenCalled();       // but notification is still delayed363            expect(beforeChangeSpy).toHaveBeenCalledWith(undefined);    // beforeChange notification happens right away364            // Second change notification is also delayed365            evalSpy.reset();366            observable('b');367            expect(computed.peek()).toEqual('a');           // peek returns previously evaluated value368            expect(evalSpy).not.toHaveBeenCalled();369            expect(notifySpy).not.toHaveBeenCalled();370            // Advance clock; Change notification happens now using the latest value notified371            evalSpy.reset();372            jasmine.Clock.tick(500);373            expect(evalSpy).toHaveBeenCalledWith('b');374            expect(notifySpy).toHaveBeenCalledWith('b');375            expect(beforeChangeSpy.calls.length).toBe(1);   // Only one beforeChange notification376        });377        it('Should run initial evaluation at first subscribe when using deferEvaluation', function() {378            // This behavior means that code using rate-limited computeds doesn't need to care if the379            // computed also has deferEvaluation. For example, the preceding test ('Should delay change380            // notifications and evaluation') will pass just as well if using deferEvaluation.381            var observable = ko.observable('a');382            var evalSpy = jasmine.createSpy('evalSpy');383            var computed = ko.computed({384                read: function () {385                    evalSpy(observable());386                    return observable();387                },388                deferEvaluation: true389            }).extend({rateLimit:500});390            expect(evalSpy).not.toHaveBeenCalled();391            var notifySpy = jasmine.createSpy('notifySpy');392            computed.subscribe(notifySpy);393            expect(evalSpy).toHaveBeenCalledWith('a');394            expect(notifySpy).not.toHaveBeenCalled();395        });396        it('Should run initial evaluation when observable is accessed when using deferEvaluation', function() {397            var observable = ko.observable('a');398            var evalSpy = jasmine.createSpy('evalSpy');399            var computed = ko.computed({400                read: function () {401                    evalSpy(observable());402                    return observable();403                },404                deferEvaluation: true405            }).extend({rateLimit:500});406            expect(evalSpy).not.toHaveBeenCalled();407            expect(computed()).toEqual('a');408            expect(evalSpy).toHaveBeenCalledWith('a');409        });410        it('Should suppress change notifications when value is changed/reverted', function() {411            var observable = ko.observable('original');412            var computed = ko.computed(function () { return observable(); }).extend({rateLimit:500});413            var notifySpy = jasmine.createSpy('notifySpy');414            computed.subscribe(notifySpy);415            var beforeChangeSpy = jasmine.createSpy('beforeChangeSpy');416            computed.subscribe(beforeChangeSpy, null, 'beforeChange');417            observable('new');                      // change value418            expect(computed()).toEqual('new');      // access computed to make sure it really has the changed value419            observable('original');                 // and then change the value back420            expect(notifySpy).not.toHaveBeenCalled();421            jasmine.Clock.tick(500);422            expect(notifySpy).not.toHaveBeenCalled();423            // Check that value is correct and notification hasn't happened424            expect(computed()).toEqual('original');425            expect(notifySpy).not.toHaveBeenCalled();426            // Changing observable to a new value still works as expected427            observable('new');428            jasmine.Clock.tick(500);429            expect(notifySpy).toHaveBeenCalledWith('new');430            expect(beforeChangeSpy).toHaveBeenCalledWith('original');431            expect(beforeChangeSpy).not.toHaveBeenCalledWith('new');432        });433        it('Should not re-evaluate if computed is disposed before timeout', function() {434            var observable = ko.observable('a');435            var evalSpy = jasmine.createSpy('evalSpy');436            var computed = ko.computed(function () { evalSpy(observable()); return observable(); }).extend({rateLimit:500});437            expect(computed()).toEqual('a');438            expect(evalSpy.calls.length).toBe(1);439            expect(evalSpy).toHaveBeenCalledWith('a');440            evalSpy.reset();441            observable('b');442            computed.dispose();443            jasmine.Clock.tick(500);444            expect(computed()).toEqual('a');445            expect(evalSpy).not.toHaveBeenCalled();446        });447        it('Should be able to re-evaluate a computed that previously threw an exception', function() {448            var observableSwitch = ko.observable(true), observableValue = ko.observable(1),449                computed = ko.computed(function() {450                    if (!observableSwitch()) {451                        throw Error("Error during computed evaluation");452                    } else {453                        return observableValue();454                    }455                }).extend({rateLimit:500});456            // Initially the computed evaluated sucessfully457            expect(computed()).toEqual(1);458            expect(function () {459                // Update observable to cause computed to throw an exception460                observableSwitch(false);461                computed();462            }).toThrow("Error during computed evaluation");463            // The value of the computed is now undefined, although currently it keeps the previous value464            // This should not try to re-evaluate and thus shouldn't throw an exception465            expect(computed()).toEqual(1);466            // The computed should not be dependent on the second observable467            expect(computed.getDependenciesCount()).toEqual(1);468            // Updating the second observable shouldn't re-evaluate computed469            observableValue(2);470            expect(computed()).toEqual(1);471            // Update the first observable to cause computed to re-evaluate472            observableSwitch(1);473            expect(computed()).toEqual(2);474        });475        it('Should delay update of dependent computed observable', function() {476            var observable = ko.observable();477            var rateLimitComputed = ko.computed(observable).extend({rateLimit:500});478            var dependentComputed = ko.computed(rateLimitComputed);479            // Check initial value480            expect(dependentComputed()).toBeUndefined();481            // Rate-limited computed is changed, but dependent computed is not482            observable('a');483            expect(rateLimitComputed()).toEqual('a');484            expect(dependentComputed()).toBeUndefined();485            // Second change also486            observable('b');487            expect(dependentComputed()).toBeUndefined();488            // Advance clock; Change notification happens now using the latest value notified489            jasmine.Clock.tick(500);490            expect(dependentComputed()).toEqual('b');491        });492        it('Should delay update of dependent pure computed observable', function() {493            var observable = ko.observable();494            var rateLimitComputed = ko.computed(observable).extend({rateLimit:500});495            var dependentComputed = ko.pureComputed(rateLimitComputed);496            // Check initial value497            expect(dependentComputed()).toBeUndefined();498            // Rate-limited computed is changed, but dependent computed is not499            observable('a');500            expect(rateLimitComputed()).toEqual('a');501            expect(dependentComputed()).toBeUndefined();502            // Second change also503            observable('b');504            expect(dependentComputed()).toBeUndefined();505            // Advance clock; Change notification happens now using the latest value notified506            jasmine.Clock.tick(500);507            expect(dependentComputed()).toEqual('b');508       });509    });510});511describe('Deferred', function() {512    beforeEach(function() {513        jasmine.Clock.useMockForTasks();514    });515    afterEach(function() {516        expect(ko.tasks.resetForTesting()).toEqual(0);517        jasmine.Clock.reset();518    });519    describe('Observable', function() {520        it('Should delay notifications', function() {521            var observable = ko.observable().extend({deferred:true});522            var notifySpy = jasmine.createSpy('notifySpy');523            observable.subscribe(notifySpy);524            observable('A');525            expect(notifySpy).not.toHaveBeenCalled();526            jasmine.Clock.tick(1);527            expect(notifySpy.argsForCall).toEqual([ ['A'] ]);528        });529        it('Should notify subscribers about only latest value', function() {530            var observable = ko.observable().extend({notify:'always', deferred:true});  // include notify:'always' to ensure notifications weren't suppressed by some other means531            var notifySpy = jasmine.createSpy('notifySpy');532            observable.subscribe(notifySpy);533            observable('A');534            observable('B');535            jasmine.Clock.tick(1);536            expect(notifySpy.argsForCall).toEqual([ ['B'] ]);537        });538        it('Set to false initially, should maintain synchronous notification', function() {539            var observable = ko.observable().extend({deferred:false});540            var notifySpy = jasmine.createSpy('notifySpy');541            observable.subscribe(notifySpy);542            observable('A');543            expect(notifySpy.argsForCall).toEqual([ ['A'] ]);544        });545        it('Should suppress notification when value is changed/reverted', function() {546            var observable = ko.observable('original').extend({deferred:true});547            var notifySpy = jasmine.createSpy('notifySpy');548            observable.subscribe(notifySpy);549            observable('new');550            expect(observable()).toEqual('new');551            observable('original');552            jasmine.Clock.tick(1);553            expect(notifySpy).not.toHaveBeenCalled();554            expect(observable()).toEqual('original');555        });556        it('Set to false, should turn off deferred notification if already turned on', function() {557            var observable = ko.observable().extend({deferred:true});558            var notifySpy = jasmine.createSpy('notifySpy');559            observable.subscribe(notifySpy);560            // First, notifications are deferred561            observable('A');562            expect(notifySpy).not.toHaveBeenCalled();563            jasmine.Clock.tick(1);564            expect(notifySpy.argsForCall).toEqual([ ['A'] ]);565            notifySpy.reset();566            observable.extend({deferred:false});567            // Now, they are synchronous568            observable('B');569            expect(notifySpy.argsForCall).toEqual([ ['B'] ]);570        });571        it('Is default behavior when "ko.options.deferUpdates" is "true"', function() {572            this.restoreAfter(ko.options, 'deferUpdates');573            ko.options.deferUpdates = true;574            var observable = ko.observable();575            var notifySpy = jasmine.createSpy('notifySpy');576            observable.subscribe(notifySpy);577            observable('A');578            expect(notifySpy).not.toHaveBeenCalled();579            jasmine.Clock.tick(1);580            expect(notifySpy.argsForCall).toEqual([ ['A'] ]);581        });582    });583    describe('Observable Array change tracking', function() {584        it('Should provide correct changelist when multiple updates are merged into one notification', function() {585            var myArray = ko.observableArray(['Alpha', 'Beta']).extend({deferred:true}),586                changelist;587            myArray.subscribe(function(changes) {588                changelist = changes;589            }, null, 'arrayChange');590            myArray.push('Gamma');591            myArray.push('Delta');592            jasmine.Clock.tick(1);593            expect(changelist).toEqual([594                { status : 'added', value : 'Gamma', index : 2 },595                { status : 'added', value : 'Delta', index : 3 }596            ]);597            changelist = undefined;598            myArray.shift();599            myArray.shift();600            jasmine.Clock.tick(1);601            expect(changelist).toEqual([602                { status : 'deleted', value : 'Alpha', index : 0 },603                { status : 'deleted', value : 'Beta', index : 1 }604            ]);605            changelist = undefined;606            myArray.push('Epsilon');607            myArray.pop();608            jasmine.Clock.tick(1);609            expect(changelist).toEqual(undefined);610        });611    });612    describe('Computed Observable', function() {613        it('Should defer notification of changes and minimize evaluation', function () {614            var timesEvaluated = 0,615                data = ko.observable('A'),616                computed = ko.computed(function () { ++timesEvaluated; return data(); }).extend({deferred:true}),617                notifySpy = jasmine.createSpy('notifySpy'),618                subscription = computed.subscribe(notifySpy);619            expect(computed()).toEqual('A');620            expect(timesEvaluated).toEqual(1);621            jasmine.Clock.tick(1);622            expect(notifySpy).not.toHaveBeenCalled();623            data('B');624            expect(timesEvaluated).toEqual(1);  // not immediately evaluated625            expect(computed()).toEqual('B');626            expect(timesEvaluated).toEqual(2);627            expect(notifySpy).not.toHaveBeenCalled();628            jasmine.Clock.tick(1);629            expect(notifySpy.calls.length).toEqual(1);630            expect(notifySpy.argsForCall).toEqual([ ['B'] ]);631        });632        it('Should notify first change of computed with deferEvaluation if value is changed to undefined', function () {633            var data = ko.observable('A'),634                computed = ko.computed(data, null, {deferEvaluation: true}).extend({deferred:true}),635                notifySpy = jasmine.createSpy('notifySpy'),636                subscription = computed.subscribe(notifySpy);637            expect(computed()).toEqual('A');638            data(undefined);639            expect(computed()).toEqual(undefined);640            expect(notifySpy).not.toHaveBeenCalled();641            jasmine.Clock.tick(1);642            expect(notifySpy.calls.length).toEqual(1);643            expect(notifySpy.argsForCall).toEqual([ [undefined] ]);644        });645        it('Should notify first change to pure computed after awakening if value changed to last notified value', function() {646            var data = ko.observable('A'),647                computed = ko.pureComputed(data).extend({deferred:true}),648                notifySpy = jasmine.createSpy('notifySpy'),649                subscription = computed.subscribe(notifySpy);650            data('B');651            expect(computed()).toEqual('B');652            expect(notifySpy).not.toHaveBeenCalled();653            jasmine.Clock.tick(1);654            expect(notifySpy.argsForCall).toEqual([ ['B'] ]);655            subscription.dispose();656            notifySpy.reset();657            data('C');658            expect(computed()).toEqual('C');659            jasmine.Clock.tick(1);660            expect(notifySpy).not.toHaveBeenCalled();661            subscription = computed.subscribe(notifySpy);662            data('B');663            expect(computed()).toEqual('B');664            expect(notifySpy).not.toHaveBeenCalled();665            jasmine.Clock.tick(1);666            expect(notifySpy.argsForCall).toEqual([ ['B'] ]);667        });668        it('Is default behavior when "ko.options.deferUpdates" is "true"', function() {669            this.restoreAfter(ko.options, 'deferUpdates');670            ko.options.deferUpdates = true;671            var data = ko.observable('A'),672                computed = ko.computed(data),673                notifySpy = jasmine.createSpy('notifySpy'),674                subscription = computed.subscribe(notifySpy);675            // Notification is deferred676            data('B');677            expect(notifySpy).not.toHaveBeenCalled();678            jasmine.Clock.tick(1);679            expect(notifySpy.argsForCall).toEqual([ ['B'] ]);680        });681    });...

Full Screen

Full Screen

test.mousetrap.js

Source:test.mousetrap.js Github

copy

Full Screen

...6});7describe('Mousetrap.bind', function() {8    describe('basic', function() {9        it('z key fires when pressing z', function() {10            var spy = sinon.spy();11            Mousetrap.bind('z', spy);12            KeyEvent.simulate('Z'.charCodeAt(0), 90);13            // really slow for some reason14            // expect(spy).to.have.been.calledOnce;15            expect(spy.callCount).to.equal(1, 'callback should fire once');16            expect(spy.args[0][0]).to.be.an.instanceOf(Event, 'first argument should be Event');17            expect(spy.args[0][1]).to.equal('z', 'second argument should be key combo');18        });19        it('z key fires from keydown', function() {20            var spy = sinon.spy();21            Mousetrap.bind('z', spy, 'keydown');22            KeyEvent.simulate('Z'.charCodeAt(0), 90);23            // really slow for some reason24            // expect(spy).to.have.been.calledOnce;25            expect(spy.callCount).to.equal(1, 'callback should fire once');26            expect(spy.args[0][0]).to.be.an.instanceOf(Event, 'first argument should be Event');27            expect(spy.args[0][1]).to.equal('z', 'second argument should be key combo');28        });29        it('z key does not fire when pressing b', function() {30            var spy = sinon.spy();31            Mousetrap.bind('z', spy);32            KeyEvent.simulate('B'.charCodeAt(0), 66);33            expect(spy.callCount).to.equal(0);34        });35        it('z key does not fire when holding a modifier key', function() {36            var spy = sinon.spy();37            var modifiers = ['ctrl', 'alt', 'meta', 'shift'];38            var charCode;39            var modifier;40            Mousetrap.bind('z', spy);41            for (var i = 0; i < 4; i++) {42                modifier = modifiers[i];43                charCode = 'Z'.charCodeAt(0);44                // character code is different when alt is pressed45                if (modifier == 'alt') {46                    charCode = 'Ω'.charCodeAt(0);47                }48                spy.reset();49                KeyEvent.simulate(charCode, 90, [modifier]);50                expect(spy.callCount).to.equal(0);51            }52        });53        it('keyup events should fire', function() {54            var spy = sinon.spy();55            Mousetrap.bind('z', spy, 'keyup');56            KeyEvent.simulate('Z'.charCodeAt(0), 90);57            expect(spy.callCount).to.equal(1, 'keyup event for "z" should fire');58            // for key held down we should only get one key up59            KeyEvent.simulate('Z'.charCodeAt(0), 90, [], document, 10);60            expect(spy.callCount).to.equal(2, 'keyup event for "z" should fire once for held down key');61        });62        it('keyup event for 0 should fire', function() {63            var spy = sinon.spy();64            Mousetrap.bind('0', spy, 'keyup');65            KeyEvent.simulate(0, 48);66            expect(spy.callCount).to.equal(1, 'keyup event for "0" should fire');67        });68        it('rebinding a key overwrites the callback for that key', function() {69            var spy1 = sinon.spy();70            var spy2 = sinon.spy();71            Mousetrap.bind('x', spy1);72            Mousetrap.bind('x', spy2);73            KeyEvent.simulate('X'.charCodeAt(0), 88);74            expect(spy1.callCount).to.equal(0, 'original callback should not fire');75            expect(spy2.callCount).to.equal(1, 'new callback should fire');76        });77        it('binding an array of keys', function() {78            var spy = sinon.spy();79            Mousetrap.bind(['a', 'b', 'c'], spy);80            KeyEvent.simulate('A'.charCodeAt(0), 65);81            expect(spy.callCount).to.equal(1, 'new callback was called');82            expect(spy.args[0][1]).to.equal('a', 'callback should match "a"');83            KeyEvent.simulate('B'.charCodeAt(0), 66);84            expect(spy.callCount).to.equal(2, 'new callback was called twice');85            expect(spy.args[1][1]).to.equal('b', 'callback should match "b"');86            KeyEvent.simulate('C'.charCodeAt(0), 67);87            expect(spy.callCount).to.equal(3, 'new callback was called three times');88            expect(spy.args[2][1]).to.equal('c', 'callback should match "c"');89        });90        it('return false should prevent default and stop propagation', function() {91            var spy = sinon.spy(function() {92                return false;93            });94            Mousetrap.bind('command+s', spy);95            KeyEvent.simulate('S'.charCodeAt(0), 83, ['meta']);96            expect(spy.callCount).to.equal(1, 'callback should fire');97            expect(spy.args[0][0]).to.be.an.instanceOf(Event, 'first argument should be Event');98            expect(spy.args[0][0].cancelBubble).to.be.True;99            expect(spy.args[0][0].defaultPrevented).to.be.True;100            // try without return false101            spy = sinon.spy();102            Mousetrap.bind('command+s', spy);103            KeyEvent.simulate('S'.charCodeAt(0), 83, ['meta']);104            expect(spy.callCount).to.equal(1, 'callback should fire');105            expect(spy.args[0][0]).to.be.an.instanceOf(Event, 'first argument should be Event');106            expect(spy.args[0][0].cancelBubble).to.be.False;107            expect(spy.args[0][0].defaultPrevented).to.be.False;108        });109        it('capslock key is ignored', function() {110            var spy = sinon.spy();111            Mousetrap.bind('a', spy);112            KeyEvent.simulate('a'.charCodeAt(0), 65);113            expect(spy.callCount).to.equal(1, 'callback should fire for lowercase a');114            spy.reset();115            KeyEvent.simulate('A'.charCodeAt(0), 65);116            expect(spy.callCount).to.equal(1, 'callback should fire for capslock A');117            spy.reset();118            KeyEvent.simulate('A'.charCodeAt(0), 65, ['shift']);119            expect(spy.callCount).to.equal(0, 'callback should not fire fort shift+a');120        });121    });122    describe('special characters', function() {123        it('binding special characters', function() {124            var spy = sinon.spy();125            Mousetrap.bind('*', spy);126            KeyEvent.simulate('*'.charCodeAt(0), 56, ['shift']);127            expect(spy.callCount).to.equal(1, 'callback should fire');128            expect(spy.args[0][1]).to.equal('*', 'callback should match *');129        });130        it('binding special characters keyup', function() {131            var spy = sinon.spy();132            Mousetrap.bind('*', spy, 'keyup');133            KeyEvent.simulate('*'.charCodeAt(0), 56, ['shift']);134            expect(spy.callCount).to.equal(1, 'callback should fire');135            expect(spy.args[0][1]).to.equal('*', 'callback should match "*"');136        });137        it('binding keys with no associated charCode', function() {138            var spy = sinon.spy();139            Mousetrap.bind('left', spy);140            KeyEvent.simulate(0, 37);141            expect(spy.callCount).to.equal(1, 'callback should fire');142            expect(spy.args[0][1]).to.equal('left', 'callback should match "left"');143        });144    });145    describe('combos with modifiers', function() {146        it('binding key combinations', function() {147            var spy = sinon.spy();148            Mousetrap.bind('command+o', spy);149            KeyEvent.simulate('O'.charCodeAt(0), 79, ['meta']);150            expect(spy.callCount).to.equal(1, 'command+o callback should fire');151            expect(spy.args[0][1]).to.equal('command+o', 'keyboard string returned is correct');152        });153        it('binding key combos with multiple modifiers', function() {154            var spy = sinon.spy();155            Mousetrap.bind('command+shift+o', spy);156            KeyEvent.simulate('O'.charCodeAt(0), 79, ['meta']);157            expect(spy.callCount).to.equal(0, 'command+o callback should not fire');158            KeyEvent.simulate('O'.charCodeAt(0), 79, ['meta', 'shift']);159            expect(spy.callCount).to.equal(1, 'command+o callback should fire');160        });161    });162    describe('sequences', function() {163        it('binding sequences', function() {164            var spy = sinon.spy();165            Mousetrap.bind('g i', spy);166            KeyEvent.simulate('G'.charCodeAt(0), 71);167            expect(spy.callCount).to.equal(0, 'callback should not fire');168            KeyEvent.simulate('I'.charCodeAt(0), 73);169            expect(spy.callCount).to.equal(1, 'callback should fire');170        });171        it('binding sequences with mixed types', function() {172            var spy = sinon.spy();173            Mousetrap.bind('g o enter', spy);174            KeyEvent.simulate('G'.charCodeAt(0), 71);175            expect(spy.callCount).to.equal(0, 'callback should not fire');176            KeyEvent.simulate('O'.charCodeAt(0), 79);177            expect(spy.callCount).to.equal(0, 'callback should not fire');178            KeyEvent.simulate(0, 13);179            expect(spy.callCount).to.equal(1, 'callback should fire');180        });181        it('binding sequences starting with modifier keys', function() {182            var spy = sinon.spy();183            Mousetrap.bind('option enter', spy);184            KeyEvent.simulate(0, 18, ['alt']);185            KeyEvent.simulate(0, 13);186            expect(spy.callCount).to.equal(1, 'callback should fire');187            spy = sinon.spy();188            Mousetrap.bind('command enter', spy);189            KeyEvent.simulate(0, 91, ['meta']);190            KeyEvent.simulate(0, 13);191            expect(spy.callCount).to.equal(1, 'callback should fire');192            spy = sinon.spy();193            Mousetrap.bind('escape enter', spy);194            KeyEvent.simulate(0, 27);195            KeyEvent.simulate(0, 13);196            expect(spy.callCount).to.equal(1, 'callback should fire');197        });198        it('key within sequence should not fire', function() {199            var spy1 = sinon.spy();200            var spy2 = sinon.spy();201            Mousetrap.bind('a', spy1);202            Mousetrap.bind('c a t', spy2);203            KeyEvent.simulate('A'.charCodeAt(0), 65);204            expect(spy1.callCount).to.equal(1, 'callback 1 should fire');205            spy1.reset();206            KeyEvent.simulate('C'.charCodeAt(0), 67);207            KeyEvent.simulate('A'.charCodeAt(0), 65);208            KeyEvent.simulate('T'.charCodeAt(0), 84);209            expect(spy1.callCount).to.equal(0, 'callback for "a" key should not fire');210            expect(spy2.callCount).to.equal(1, 'callback for "c a t" sequence should fire');211        });212        it('keyup at end of sequence should not fire', function() {213            var spy1 = sinon.spy();214            var spy2 = sinon.spy();215            Mousetrap.bind('t', spy1, 'keyup');216            Mousetrap.bind('b a t', spy2);217            KeyEvent.simulate('B'.charCodeAt(0), 66);218            KeyEvent.simulate('A'.charCodeAt(0), 65);219            KeyEvent.simulate('T'.charCodeAt(0), 84);220            expect(spy1.callCount).to.equal(0, 'callback for "t" keyup should not fire');221            expect(spy2.callCount).to.equal(1, 'callback for "b a t" sequence should fire');222        });223        it('keyup sequences should work', function() {224            var spy = sinon.spy();225            Mousetrap.bind('b a t', spy, 'keyup');226            KeyEvent.simulate('b'.charCodeAt(0), 66);227            KeyEvent.simulate('a'.charCodeAt(0), 65);228            // hold the last key down for a while229            KeyEvent.simulate('t'.charCodeAt(0), 84, [], document, 10);230            expect(spy.callCount).to.equal(1, 'callback for "b a t" sequence should fire on keyup');231        });232        it('extra spaces in sequences should be ignored', function() {233            var spy = sinon.spy();234            Mousetrap.bind('b   a  t', spy);235            KeyEvent.simulate('b'.charCodeAt(0), 66);236            KeyEvent.simulate('a'.charCodeAt(0), 65);237            KeyEvent.simulate('t'.charCodeAt(0), 84);238            expect(spy.callCount).to.equal(1, 'callback for "b a t" sequence should fire');239        });240        it('modifiers and sequences play nicely', function() {241            var spy1 = sinon.spy();242            var spy2 = sinon.spy();243            Mousetrap.bind('ctrl a', spy1);244            Mousetrap.bind('ctrl+b', spy2);245            KeyEvent.simulate(0, 17, ['ctrl']);246            KeyEvent.simulate('A'.charCodeAt(0), 65);247            expect(spy1.callCount).to.equal(1, '"ctrl a" should fire');248            KeyEvent.simulate('B'.charCodeAt(0), 66, ['ctrl']);249            expect(spy2.callCount).to.equal(1, '"ctrl+b" should fire');250        });251        it('sequences that start the same work', function() {252            var spy1 = sinon.spy();253            var spy2 = sinon.spy();254            Mousetrap.bind('g g l', spy2);255            Mousetrap.bind('g g o', spy1);256            KeyEvent.simulate('g'.charCodeAt(0), 71);257            KeyEvent.simulate('g'.charCodeAt(0), 71);258            KeyEvent.simulate('o'.charCodeAt(0), 79);259            expect(spy1.callCount).to.equal(1, '"g g o" should fire');260            expect(spy2.callCount).to.equal(0, '"g g l" should not fire');261            spy1.reset();262            spy2.reset();263            KeyEvent.simulate('g'.charCodeAt(0), 71);264            KeyEvent.simulate('g'.charCodeAt(0), 71);265            KeyEvent.simulate('l'.charCodeAt(0), 76);266            expect(spy1.callCount).to.equal(0, '"g g o" should not fire');267            expect(spy2.callCount).to.equal(1, '"g g l" should fire');268        });269        it('sequences should not fire subsequences', function() {270            var spy1 = sinon.spy();271            var spy2 = sinon.spy();272            Mousetrap.bind('a b c', spy1);273            Mousetrap.bind('b c', spy2);274            KeyEvent.simulate('A'.charCodeAt(0), 65);275            KeyEvent.simulate('B'.charCodeAt(0), 66);276            KeyEvent.simulate('C'.charCodeAt(0), 67);277            expect(spy1.callCount).to.equal(1, '"a b c" should fire');278            expect(spy2.callCount).to.equal(0, '"b c" should not fire');279            spy1.reset();280            spy2.reset();281            Mousetrap.bind('option b', spy1);282            Mousetrap.bind('a option b', spy2);283            KeyEvent.simulate('A'.charCodeAt(0), 65);284            KeyEvent.simulate(0, 18, ['alt']);285            KeyEvent.simulate('B'.charCodeAt(0), 66);286            expect(spy1.callCount).to.equal(0, '"option b" should not fire');287            expect(spy2.callCount).to.equal(1, '"a option b" should fire');288        });289        it('rebinding same sequence should override previous', function() {290            var spy1 = sinon.spy();291            var spy2 = sinon.spy();292            Mousetrap.bind('a b c', spy1);293            Mousetrap.bind('a b c', spy2);294            KeyEvent.simulate('a'.charCodeAt(0), 65);295            KeyEvent.simulate('b'.charCodeAt(0), 66);296            KeyEvent.simulate('c'.charCodeAt(0), 67);297            expect(spy1.callCount).to.equal(0, 'first callback should not fire');298            expect(spy2.callCount).to.equal(1, 'second callback should fire');299        });300        it('broken sequences', function() {301            var spy = sinon.spy();302            Mousetrap.bind('h a t', spy);303            KeyEvent.simulate('h'.charCodeAt(0), 72);304            KeyEvent.simulate('e'.charCodeAt(0), 69);305            KeyEvent.simulate('a'.charCodeAt(0), 65);306            KeyEvent.simulate('r'.charCodeAt(0), 82);307            KeyEvent.simulate('t'.charCodeAt(0), 84);308            expect(spy.callCount).to.equal(0, 'sequence for "h a t" should not fire for "h e a r t"');309        });310        it('sequences containing combos should work', function() {311            var spy = sinon.spy();312            Mousetrap.bind('a ctrl+b', spy);313            KeyEvent.simulate('a'.charCodeAt(0), 65);314            KeyEvent.simulate('B'.charCodeAt(0), 66, ['ctrl']);315            expect(spy.callCount).to.equal(1, '"a ctrl+b" should fire');316            Mousetrap.unbind('a ctrl+b');317            spy = sinon.spy();318            Mousetrap.bind('ctrl+b a', spy);319            KeyEvent.simulate('b'.charCodeAt(0), 66, ['ctrl']);320            KeyEvent.simulate('a'.charCodeAt(0), 65);321            expect(spy.callCount).to.equal(1, '"ctrl+b a" should fire');322        });323        it('sequences starting with spacebar should work', function() {324            var spy = sinon.spy();325            Mousetrap.bind('a space b c', spy);326            KeyEvent.simulate('a'.charCodeAt(0), 65);327            KeyEvent.simulate(32, 32);328            KeyEvent.simulate('b'.charCodeAt(0), 66);329            KeyEvent.simulate('c'.charCodeAt(0), 67);330            expect(spy.callCount).to.equal(1, '"a space b c" should fire');331        });332        it('konami code', function() {333            var spy = sinon.spy();334            Mousetrap.bind('up up down down left right left right b a enter', spy);335            KeyEvent.simulate(0, 38);336            KeyEvent.simulate(0, 38);337            KeyEvent.simulate(0, 40);338            KeyEvent.simulate(0, 40);339            KeyEvent.simulate(0, 37);340            KeyEvent.simulate(0, 39);341            KeyEvent.simulate(0, 37);342            KeyEvent.simulate(0, 39);343            KeyEvent.simulate('b'.charCodeAt(0), 66);344            KeyEvent.simulate('a'.charCodeAt(0), 65);345            KeyEvent.simulate(0, 13);346            expect(spy.callCount).to.equal(1, 'konami code should fire');347        });348        it('sequence timer resets', function() {349            var spy = sinon.spy();350            var clock = sinon.useFakeTimers();351            Mousetrap.bind('h a t', spy);352            KeyEvent.simulate('h'.charCodeAt(0), 72);353            clock.tick(600);354            KeyEvent.simulate('a'.charCodeAt(0), 65);355            clock.tick(900);356            KeyEvent.simulate('t'.charCodeAt(0), 84);357            expect(spy.callCount).to.equal(1, 'sequence should fire after waiting');358            clock.restore();359        });360        it('sequences timeout', function() {361            var spy = sinon.spy();362            var clock = sinon.useFakeTimers();363            Mousetrap.bind('g t', spy);364            KeyEvent.simulate('g'.charCodeAt(0), 71);365            clock.tick(1000);366            KeyEvent.simulate('t'.charCodeAt(0), 84);367            expect(spy.callCount).to.equal(0, 'sequence callback should not fire');368            clock.restore();369        });370    });371    describe('default actions', function() {372        var keys = {373            keypress: [374                ['a', 65],375                ['A', 65, ['shift']],376                ['7', 55],377                ['?', 191],378                ['*', 56],379                ['+', 187],380                ['$', 52],381                ['[', 219],382                ['.', 190]383            ],384            keydown: [385                ['shift+\'', 222, ['shift']],386                ['shift+a', 65, ['shift']],387                ['shift+5', 53, ['shift']],388                ['command+shift+p', 80, ['meta', 'shift']],389                ['space', 32],390                ['left', 37]391            ]392        };393        function getCallback(key, keyCode, type, modifiers) {394            return function() {395                var spy = sinon.spy();396                Mousetrap.bind(key, spy);397                KeyEvent.simulate(key.charCodeAt(0), keyCode, modifiers);398                expect(spy.callCount).to.equal(1);399                expect(spy.args[0][0].type).to.equal(type);400            };401        }402        for (var type in keys) {403            for (var i = 0; i < keys[type].length; i++) {404                var key = keys[type][i][0];405                var keyCode = keys[type][i][1];406                var modifiers = keys[type][i][2] || [];407                it('"' + key + '" uses "' + type + '"', getCallback(key, keyCode, type, modifiers));408            }409        }410    });411});412describe('Mousetrap.unbind', function() {413    it('unbind works', function() {414        var spy = sinon.spy();415        Mousetrap.bind('a', spy);416        KeyEvent.simulate('a'.charCodeAt(0), 65);417        expect(spy.callCount).to.equal(1, 'callback for a should fire');418        Mousetrap.unbind('a');419        KeyEvent.simulate('a'.charCodeAt(0), 65);420        expect(spy.callCount).to.equal(1, 'callback for a should not fire after unbind');421    });422    it('unbind accepts an array', function() {423        var spy = sinon.spy();424        Mousetrap.bind(['a', 'b', 'c'], spy);425        KeyEvent.simulate('a'.charCodeAt(0), 65);426        KeyEvent.simulate('b'.charCodeAt(0), 66);427        KeyEvent.simulate('c'.charCodeAt(0), 67);428        expect(spy.callCount).to.equal(3, 'callback should have fired 3 times');429        Mousetrap.unbind(['a', 'b', 'c']);430        KeyEvent.simulate('a'.charCodeAt(0), 65);431        KeyEvent.simulate('b'.charCodeAt(0), 66);432        KeyEvent.simulate('c'.charCodeAt(0), 67);433        expect(spy.callCount).to.equal(3, 'callback should not fire after unbind');434    });...

Full Screen

Full Screen

messages.js

Source:messages.js Github

copy

Full Screen

...4var swallow = require("./common").swallow;5describe("Messages", function () {6    describe("about call count", function () {7        it("should be correct for the base cases", function () {8            var spy = sinon.spy();9            expect(function () {10                spy.should.have.been.called;11            }).to.throw("expected spy to have been called at least once, but it was never called");12            expect(function () {13                spy.should.have.been.calledOnce;14            }).to.throw("expected spy to have been called exactly once, but it was called 0 times");15            expect(function () {16                spy.should.have.been.calledTwice;17            }).to.throw("expected spy to have been called exactly twice, but it was called 0 times");18            expect(function () {19                spy.should.have.been.calledThrice;20            }).to.throw("expected spy to have been called exactly thrice, but it was called 0 times");21            expect(function () {22                spy.should.have.callCount(1);23            }).to.throw("expected spy to have been called exactly once, but it was called 0 times");24            expect(function () {25                spy.should.have.callCount(4);26            }).to.throw("expected spy to have been called exactly 4 times, but it was called 0 times");27        });28        it("should be correct for the negated cases", function () {29            var calledOnce = sinon.spy();30            var calledTwice = sinon.spy();31            var calledThrice = sinon.spy();32            var calledFourTimes = sinon.spy();33            calledOnce();34            calledTwice();35            calledTwice();36            calledThrice();37            calledThrice();38            calledThrice();39            calledFourTimes();40            calledFourTimes();41            calledFourTimes();42            calledFourTimes();43            expect(function () {44                calledOnce.should.not.have.been.called;45            }).to.throw("expected spy to not have been called");46            expect(function () {47                calledOnce.should.not.have.been.calledOnce;48            }).to.throw("expected spy to not have been called exactly once");49            expect(function () {50                calledTwice.should.not.have.been.calledTwice;51            }).to.throw("expected spy to not have been called exactly twice");52            expect(function () {53                calledThrice.should.not.have.been.calledThrice;54            }).to.throw("expected spy to not have been called exactly thrice");55            expect(function () {56                calledOnce.should.not.have.callCount(1);57            }).to.throw("expected spy to not have been called exactly once");58            expect(function () {59                calledFourTimes.should.not.have.callCount(4);60            }).to.throw("expected spy to not have been called exactly 4 times");61        });62    });63    describe("about call order", function () {64        it("should be correct for the base cases", function () {65            var spyA = sinon.spy();66            var spyB = sinon.spy();67            spyA.displayName = "spyA";68            spyB.displayName = "spyB";69            expect(function () {70                spyA.should.have.been.calledBefore(spyB);71            }).to.throw("expected spyA to have been called before function spyB() {}");72            if (spyA.calledImmediatelyBefore) {73                expect(function () {74                    spyA.should.have.been.calledImmediatelyBefore(spyB);75                }).to.throw("expected spyA to have been called immediately before function spyB() {}");76            }77            expect(function () {78                spyB.should.have.been.calledAfter(spyA);79            }).to.throw("expected spyB to have been called after function spyA() {}");80            if (spyB.calledImmediatelyAfter) {81                expect(function () {82                    spyB.should.have.been.calledImmediatelyAfter(spyA);83                }).to.throw("expected spyB to have been called immediately after function spyA() {}");84            }85        });86        it("should be correct for the negated cases", function () {87            var spyA = sinon.spy();88            var spyB = sinon.spy();89            spyA.displayName = "spyA";90            spyB.displayName = "spyB";91            spyA();92            spyB();93            expect(function () {94                spyA.should.not.have.been.calledBefore(spyB);95            }).to.throw("expected spyA to not have been called before function spyB() {}");96            if (spyA.calledImmediatelyBefore) {97                expect(function () {98                    spyA.should.not.have.been.calledImmediatelyBefore(spyB);99                }).to.throw("expected spyA to not have been called immediately before function spyB() {}");100            }101            expect(function () {102                spyB.should.not.have.been.calledAfter(spyA);103            }).to.throw("expected spyB to not have been called after function spyA() {}");104            if (spyB.calledImmediatelyAfter) {105                expect(function () {106                    spyB.should.not.have.been.calledImmediatelyAfter(spyA);107                }).to.throw("expected spyB to not have been called immediately after function spyA() {}");108            }109        });110    });111    describe("about call context", function () {112        it("should be correct for the basic case", function () {113            var spy = sinon.spy();114            var context = {};115            var badContext = { x: "y" };116            spy.call(badContext);117            var expected = "expected spy to have been called with {  } as this, but it was called with " +118                           spy.printf("%t") + " instead";119            expect(function () {120                spy.should.have.been.calledOn(context);121            }).to.throw(expected);122            expect(function () {123                spy.getCall(0).should.have.been.calledOn(context);124            }).to.throw(expected);125        });126        it("should be correct for the negated case", function () {127            var spy = sinon.spy();128            var context = {};129            spy.call(context);130            var expected = "expected spy to not have been called with {  } as this";131            expect(function () {132                spy.should.not.have.been.calledOn(context);133            }).to.throw(expected);134            expect(function () {135                spy.getCall(0).should.not.have.been.calledOn(context);136            }).to.throw(expected);137        });138        it("should be correct for the always case", function () {139            var spy = sinon.spy();140            var context = {};141            var badContext = { x: "y" };142            spy.call(badContext);143            var expected = "expected spy to always have been called with {  } as this, but it was called with " +144                           spy.printf("%t") + " instead";145            expect(function () {146                spy.should.always.have.been.calledOn(context);147            }).to.throw(expected);148        });149    });150    describe("about calling with new", function () {151        /* eslint-disable new-cap, no-new */152        it("should be correct for the basic case", function () {153            var spy = sinon.spy();154            spy();155            var expected = "expected spy to have been called with new";156            expect(function () {157                spy.should.have.been.calledWithNew;158            }).to.throw(expected);159            expect(function () {160                spy.getCall(0).should.have.been.calledWithNew;161            }).to.throw(expected);162        });163        it("should be correct for the negated case", function () {164            var spy = sinon.spy();165            new spy();166            var expected = "expected spy to not have been called with new";167            expect(function () {168                spy.should.not.have.been.calledWithNew;169            }).to.throw(expected);170            expect(function () {171                spy.getCall(0).should.not.have.been.calledWithNew;172            }).to.throw(expected);173        });174        it("should be correct for the always case", function () {175            var spy = sinon.spy();176            new spy();177            spy();178            var expected = "expected spy to always have been called with new";179            expect(function () {180                spy.should.always.have.been.calledWithNew;181            }).to.throw(expected);182        });183        /* eslint-enable new-cap, no-new */184    });185    describe("about call arguments", function () {186        it("should be correct for the basic cases", function () {187            var spy = sinon.spy();188            spy(1, 2, 3);189            expect(function () {190                spy.should.have.been.calledWith("a", "b", "c");191            }).to.throw("expected spy to have been called with arguments a, b, c\n    spy(1, 2, 3)");192            expect(function () {193                spy.should.have.been.calledWithExactly("a", "b", "c");194            }).to.throw("expected spy to have been called with exact arguments a, b, c\n    spy(1, 2, 3)");195            expect(function () {196                spy.should.have.been.calledWithMatch(sinon.match("foo"));197            }).to.throw("expected spy to have been called with arguments matching match(\"foo\")\n    spy(1, 2, 3)");198            expect(function () {199                spy.getCall(0).should.have.been.calledWith("a", "b", "c");200            }).to.throw("expected spy to have been called with arguments a, b, c\n    spy(1, 2, 3)");201            expect(function () {202                spy.getCall(0).should.have.been.calledWithExactly("a", "b", "c");203            }).to.throw("expected spy to have been called with exact arguments a, b, c\n    spy(1, 2, 3)");204            expect(function () {205                spy.getCall(0).should.have.been.calledWithMatch(sinon.match("foo"));206            }).to.throw("expected spy to have been called with arguments matching match(\"foo\")\n    spy(1, 2, 3)");207        });208        it("should be correct for the negated cases", function () {209            var spy = sinon.spy();210            spy(1, 2, 3);211            expect(function () {212                spy.should.not.have.been.calledWith(1, 2, 3);213            }).to.throw("expected spy to not have been called with arguments 1, 2, 3");214            expect(function () {215                spy.should.not.have.been.calledWithExactly(1, 2, 3);216            }).to.throw("expected spy to not have been called with exact arguments 1, 2, 3");217            expect(function () {218                spy.should.not.have.been.calledWithMatch(sinon.match(1));219            }).to.throw("expected spy to not have been called with arguments matching match(1)");220            expect(function () {221                spy.getCall(0).should.not.have.been.calledWith(1, 2, 3);222            }).to.throw("expected spy to not have been called with arguments 1, 2, 3");223            expect(function () {224                spy.getCall(0).should.not.have.been.calledWithExactly(1, 2, 3);225            }).to.throw("expected spy to not have been called with exact arguments 1, 2, 3");226            expect(function () {227                spy.getCall(0).should.not.have.been.calledWithMatch(sinon.match(1));228            }).to.throw("expected spy to not have been called with arguments matching match(1)");229        });230        it("should be correct for the always cases", function () {231            var spy = sinon.spy();232            spy(1, 2, 3);233            spy("a", "b", "c");234            var expected = /expected spy to always have been called with arguments 1, 2, 3/;235            expect(function () {236                spy.should.always.have.been.calledWith(1, 2, 3);237            }).to.throw(expected);238            var expectedExactly = /expected spy to always have been called with exact arguments 1, 2, 3/;239            expect(function () {240                spy.should.always.have.been.calledWithExactly(1, 2, 3);241            }).to.throw(expectedExactly);242            var expectedMatch = /expected spy to always have been called with arguments matching match\(1\)/;243            expect(function () {244                spy.should.always.have.been.calledWithMatch(sinon.match(1));245            }).to.throw(expectedMatch);246        });247    });248    describe("about returning", function () {249        it("should be correct for the basic case", function () {250            var spy = sinon.spy.create(function () {251                return 1;252            });253            spy();254            expect(function () {255                spy.should.have.returned(2);256            }).to.throw("expected spy to have returned 2");257            expect(function () {258                spy.getCall(0).should.have.returned(2);259            }).to.throw("expected spy to have returned 2");260        });261        it("should be correct for the negated case", function () {262            var spy = sinon.spy.create(function () {263                return 1;264            });265            spy();266            expect(function () {267                spy.should.not.have.returned(1);268            }).to.throw("expected spy to not have returned 1");269            expect(function () {270                spy.getCall(0).should.not.have.returned(1);271            }).to.throw("expected spy to not have returned 1");272        });273        it("should be correct for the always case", function () {274            var spy = sinon.spy.create(function () {275                return 1;276            });277            spy();278            expect(function () {279                spy.should.always.have.returned(2);280            }).to.throw("expected spy to always have returned 2");281        });282    });283    describe("about throwing", function () {284        it("should be correct for the basic cases", function () {285            var spy = sinon.spy();286            var throwingSpy = sinon.spy.create(function () {287                throw new Error();288            });289            spy();290            swallow(throwingSpy);291            expect(function () {292                spy.should.have.thrown();293            }).to.throw("expected spy to have thrown");294            expect(function () {295                spy.getCall(0).should.have.thrown();296            }).to.throw("expected spy to have thrown");297            expect(function () {298                throwingSpy.should.have.thrown("TypeError");299            }).to.throw("expected spy to have thrown TypeError");300            expect(function () {301                throwingSpy.getCall(0).should.have.thrown("TypeError");302            }).to.throw("expected spy to have thrown TypeError");303            expect(function () {304                throwingSpy.should.have.thrown({ message: "x" });305            }).to.throw('expected spy to have thrown { message: "x" }');306            expect(function () {307                throwingSpy.getCall(0).should.have.thrown({ message: "x" });308            }).to.throw('expected spy to have thrown { message: "x" }');309        });310        it("should be correct for the negated cases", function () {311            var error = new Error("boo!");312            var spy = sinon.spy.create(function () {313                throw error;314            });315            swallow(spy);316            expect(function () {317                spy.should.not.have.thrown();318            }).to.throw("expected spy to not have thrown");319            expect(function () {320                spy.getCall(0).should.not.have.thrown();321            }).to.throw("expected spy to not have thrown");322            expect(function () {323                spy.should.not.have.thrown("Error");324            }).to.throw("expected spy to not have thrown Error");325            expect(function () {326                spy.getCall(0).should.not.have.thrown("Error");327            }).to.throw("expected spy to not have thrown Error");328            expect(function () {329                spy.should.not.have.thrown(error);330            }).to.throw("expected spy to not have thrown Error: boo!");331            expect(function () {332                spy.getCall(0).should.not.have.thrown(error);333            }).to.throw("expected spy to not have thrown Error: boo!");334        });335        it("should be correct for the always cases", function () {336            var spy = sinon.spy();337            var throwingSpy = sinon.spy.create(function () {338                throw new Error();339            });340            spy();341            swallow(throwingSpy);342            expect(function () {343                spy.should.have.always.thrown();344            }).to.throw("expected spy to always have thrown");345            expect(function () {346                throwingSpy.should.have.always.thrown("TypeError");347            }).to.throw("expected spy to always have thrown TypeError");348            expect(function () {349                throwingSpy.should.have.always.thrown({ message: "x" });350            }).to.throw('expected spy to always have thrown { message: "x" }');351        });352    });353    describe("when used on a non-spy/non-call", function () {354        function notSpy() {355            // Contents don't matter356        }357        it("should be informative for properties", function () {358            expect(function () {359                notSpy.should.have.been.called;360            }).to.throw(TypeError, /not a spy/);361        });362        it("should be informative for methods", function () {363            expect(function () {364                notSpy.should.have.been.calledWith("foo");365            }).to.throw(TypeError, /not a spy/);366        });367    });368    it("should not trigger getters for passing assertions", function () {369        var obj = {};370        var getterCalled = false;371        Object.defineProperty(obj, "getter", {372            get: function () {373                getterCalled = true;374            },375            enumerable: true376        });377        var spy = sinon.spy();378        spy(obj);379        spy.should.have.been.calledWith(obj);380        expect(getterCalled).to.be.false;381    });...

Full Screen

Full Screen

view_helpers.js

Source:view_helpers.js Github

copy

Full Screen

1/**2 * Provides helper methods for invoking Studio modal windows in Jasmine tests.3 */4define(["jquery", "js/views/feedback_notification", "js/views/feedback_prompt", "js/common_helpers/template_helpers"],5    function($, NotificationView, Prompt, TemplateHelpers) {6        var installViewTemplates, createFeedbackSpy, verifyFeedbackShowing,7            verifyFeedbackHidden, createNotificationSpy, verifyNotificationShowing,8            verifyNotificationHidden, createPromptSpy, confirmPrompt, inlineEdit, verifyInlineEditChange,9            installMockAnalytics, removeMockAnalytics, verifyPromptShowing, verifyPromptHidden;10        installViewTemplates = function(append) {11            TemplateHelpers.installTemplate('system-feedback', !append);12            appendSetFixtures('<div id="page-notification"></div>');13        };14        createFeedbackSpy = function(type, intent) {15            var feedbackSpy = spyOnConstructor(type, intent, ['show', 'hide']);16            feedbackSpy.show.andReturn(feedbackSpy);17            return feedbackSpy;18        };19        verifyFeedbackShowing = function(feedbackSpy, text) {20            var options;21            expect(feedbackSpy.constructor).toHaveBeenCalled();22            expect(feedbackSpy.show).toHaveBeenCalled();23            expect(feedbackSpy.hide).not.toHaveBeenCalled();24            options = feedbackSpy.constructor.mostRecentCall.args[0];25            expect(options.title).toMatch(text);26        };27        verifyFeedbackHidden = function(feedbackSpy) {28            expect(feedbackSpy.hide).toHaveBeenCalled();29        };30        createNotificationSpy = function(type) {31            return createFeedbackSpy(NotificationView, type || 'Mini');32        };33        verifyNotificationShowing = function(notificationSpy, text) {34            verifyFeedbackShowing.apply(this, arguments);35        };36        verifyNotificationHidden = function(notificationSpy) {37            verifyFeedbackHidden.apply(this, arguments);38        };39        createPromptSpy = function(type) {40            return createFeedbackSpy(Prompt, type || 'Warning');41        };42        confirmPrompt = function(promptSpy, pressSecondaryButton) {43            expect(promptSpy.constructor).toHaveBeenCalled();44            if (pressSecondaryButton) {45                promptSpy.constructor.mostRecentCall.args[0].actions.secondary.click(promptSpy);46            } else {47                promptSpy.constructor.mostRecentCall.args[0].actions.primary.click(promptSpy);48            }49        };50        verifyPromptShowing = function(promptSpy, text) {51            verifyFeedbackShowing.apply(this, arguments);52        };53        verifyPromptHidden = function(promptSpy) {54            verifyFeedbackHidden.apply(this, arguments);55        };56        installMockAnalytics = function() {57            window.analytics = jasmine.createSpyObj('analytics', ['track']);58            window.course_location_analytics = jasmine.createSpy();59        };60        removeMockAnalytics = function() {61            delete window.analytics;62            delete window.course_location_analytics;63        };64        inlineEdit = function(editorWrapper, newValue) {65            var inputField = editorWrapper.find('.xblock-field-input'),66                editButton = editorWrapper.find('.xblock-field-value-edit');67            editButton.click();68            expect(editorWrapper).toHaveClass('is-editing');69            inputField.val(newValue);70            return inputField;71        };72        verifyInlineEditChange = function(editorWrapper, expectedValue, failedValue) {73            var displayName = editorWrapper.find('.xblock-field-value');74            expect(displayName.text()).toBe(expectedValue);75            if (failedValue) {76                expect(editorWrapper).toHaveClass('is-editing');77            } else {78                expect(editorWrapper).not.toHaveClass('is-editing');79            }80        };81        return {82            'installViewTemplates': installViewTemplates,83            'createNotificationSpy': createNotificationSpy,84            'verifyNotificationShowing': verifyNotificationShowing,85            'verifyNotificationHidden': verifyNotificationHidden,86            'confirmPrompt': confirmPrompt,87            'createPromptSpy': createPromptSpy,88            'verifyPromptShowing': verifyPromptShowing,89            'verifyPromptHidden': verifyPromptHidden,90            'inlineEdit': inlineEdit,91            'verifyInlineEditChange': verifyInlineEditChange,92            'installMockAnalytics': installMockAnalytics,93            'removeMockAnalytics': removeMockAnalytics94        };...

Full Screen

Full Screen

Number.spec.js

Source:Number.spec.js Github

copy

Full Screen

1describe('Number helper', function () {2  //3  // Handsontable.helper.rangeEach4  //5  describe('rangeEach', function() {6    it("should iterate increasingly, when `from` and `to` arguments are passed and `from` number is lower then `to`", function () {7      var rangeEach = Handsontable.helper.rangeEach;8      var spy = jasmine.createSpy();9      rangeEach(-1, 2, spy);10      expect(spy.calls.count()).toBe(4);11      expect(spy.calls.argsFor(0)).toEqual([-1]);12      expect(spy.calls.argsFor(1)).toEqual([0]);13      expect(spy.calls.argsFor(2)).toEqual([1]);14      expect(spy.calls.argsFor(3)).toEqual([2]);15    });16    it("should iterate only once, when `from` and `to` arguments are equal", function () {17      var rangeEach = Handsontable.helper.rangeEach;18      var spy = jasmine.createSpy();19      rangeEach(10, 10, spy);20      expect(spy.calls.count()).toBe(1);21      expect(spy.calls.argsFor(0)).toEqual([10]);22    });23    it("should iterate only once, when `from` and `to` arguments are equal and from value is zero", function () {24      var rangeEach = Handsontable.helper.rangeEach;25      var spy = jasmine.createSpy();26      rangeEach(0, spy);27      expect(spy.calls.count()).toBe(1);28      expect(spy.calls.argsFor(0)).toEqual([0]);29    });30    it("should iterate increasingly from 0, when only `from` argument is passed", function () {31      var rangeEach = Handsontable.helper.rangeEach;32      var spy = jasmine.createSpy();33      rangeEach(4, spy);34      expect(spy.calls.count()).toBe(5);35      expect(spy.calls.argsFor(0)).toEqual([0]);36      expect(spy.calls.argsFor(4)).toEqual([4]);37    });38    it("shouldn\'t iterate decreasingly, when `from` and `to` arguments are passed and `from` number is higher then `to`", function () {39      var rangeEach = Handsontable.helper.rangeEach;40      var spy = jasmine.createSpy();41      rangeEach(1, -3, spy);42      expect(spy.calls.count()).toBe(0);43    });44  });45  //46  // Handsontable.helper.rangeEachReverse47  //48  describe('rangeEachReverse', function() {49    it("should iterate decreasingly, when `from` and `to` arguments are passed and `from` number is higher then `to`", function () {50      var rangeEachReverse = Handsontable.helper.rangeEachReverse;51      var spy = jasmine.createSpy();52      rangeEachReverse(2, -1, spy);53      expect(spy.calls.count()).toBe(4);54      expect(spy.calls.argsFor(0)).toEqual([2]);55      expect(spy.calls.argsFor(1)).toEqual([1]);56      expect(spy.calls.argsFor(2)).toEqual([0]);57      expect(spy.calls.argsFor(3)).toEqual([-1]);58    });59    it("should iterate only once, when `from` and `to` arguments are equal", function () {60      var rangeEachReverse = Handsontable.helper.rangeEachReverse;61      var spy = jasmine.createSpy();62      rangeEachReverse(10, 10, spy);63      expect(spy.calls.count()).toBe(1);64      expect(spy.calls.argsFor(0)).toEqual([10]);65    });66    it("should iterate only once, when `from` and `to` arguments are equal and from value is zero", function () {67      var rangeEachReverse = Handsontable.helper.rangeEachReverse;68      var spy = jasmine.createSpy();69      rangeEachReverse(0, spy);70      expect(spy.calls.count()).toBe(1);71      expect(spy.calls.argsFor(0)).toEqual([0]);72    });73    it("should iterate decreasingly to 0, when only `from` argument is passed", function () {74      var rangeEachReverse = Handsontable.helper.rangeEachReverse;75      var spy = jasmine.createSpy();76      rangeEachReverse(4, spy);77      expect(spy.calls.count()).toBe(5);78      expect(spy.calls.argsFor(0)).toEqual([4]);79      expect(spy.calls.argsFor(4)).toEqual([0]);80    });81    it("shouldn\'t iterate increasingly, when `from` and `to` arguments are passed and `from` number is higher then `to`", function () {82      var rangeEachReverse = Handsontable.helper.rangeEachReverse;83      var spy = jasmine.createSpy();84      rangeEachReverse(1, 5, spy);85      expect(spy.calls.count()).toBe(0);86    });87  });...

Full Screen

Full Screen

spy.js

Source:spy.js Github

copy

Full Screen

1import $ from 'jquery';2import _ from 'lodash';3import { SpyModesRegistryProvider } from 'ui/registry/spy_modes';4import { uiModules } from 'ui/modules';5import spyTemplate from 'ui/visualize/spy.html';6uiModules7  .get('app/visualize')8  .directive('visualizeSpy', function (Private, $compile) {9    const spyModes = Private(SpyModesRegistryProvider);10    const defaultMode = spyModes.inOrder[0].name;11    return {12      restrict: 'E',13      template: spyTemplate,14      link: function ($scope, $el) {15        let currentSpy;16        const $container = $el.find('[data-spy-content-container]');17        let fullPageSpy = _.get($scope.spy, 'mode.fill', false);18        $scope.modes = spyModes;19        $scope.spy.params = $scope.spy.params || {};20        function getSpyObject(name) {21          name = _.isUndefined(name) ? $scope.spy.mode.name : name;22          fullPageSpy = (_.isNull(name)) ? false : fullPageSpy;23          return {24            name: name,25            fill: fullPageSpy,26          };27        }28        function setSpyMode(modeName) {29          if (!_.isString(modeName)) modeName = null;30          $scope.spy.mode = getSpyObject(modeName);31          $scope.$emit('render');32        }33        const renderSpy = function (spyName) {34          const newMode = $scope.modes.byName[spyName];35          // clear the current value36          if (currentSpy) {37            currentSpy.$container && currentSpy.$container.remove();38            currentSpy.$scope && currentSpy.$scope.$destroy();39            $scope.spy.mode = {};40            currentSpy = null;41          }42          // no further changes43          if (!newMode) return;44          // update the spy mode and append to the container45          const selectedSpyMode = getSpyObject(newMode.name);46          $scope.spy.mode = selectedSpyMode;47          $scope.selectedModeName = selectedSpyMode.name;48          currentSpy = _.assign({49            $scope: $scope.$new(),50            $container: $('<div class="visualize-spy-content">').appendTo($container)51          }, $scope.spy.mode);52          currentSpy.$container.append($compile(newMode.template)(currentSpy.$scope));53          newMode.link && newMode.link(currentSpy.$scope, currentSpy.$container);54        };55        $scope.toggleDisplay = function () {56          const modeName = _.get($scope.spy, 'mode.name');57          setSpyMode(modeName ? null : defaultMode);58        };59        $scope.toggleFullPage = function () {60          fullPageSpy = !fullPageSpy;61          $scope.spy.mode = getSpyObject();62        };63        $scope.onSpyModeChange = function onSpyModeChange() {64          setSpyMode($scope.selectedModeName);65        };66        if ($scope.uiState) {67          // sync external uiState changes68          const syncUIState = () => $scope.spy.mode = $scope.uiState.get('spy.mode');69          $scope.uiState.on('change', syncUIState);70          $scope.$on('$destroy', () => $scope.uiState.off('change', syncUIState));71        }72        // re-render the spy when the name of fill modes change73        $scope.$watchMulti([74          'spy.mode.name',75          'spy.mode.fill'76        ], function (newVals, oldVals) {77          // update the ui state, but only if it really changes78          const changedVals = newVals.filter((val) => !_.isUndefined(val)).length > 0;79          if (changedVals && !_.isEqual(newVals, oldVals)) {80            if ($scope.uiState) $scope.uiState.set('spy.mode', $scope.spy.mode);81          }82          // ensure the fill mode is synced83          fullPageSpy = _.get($scope.spy, 'mode.fill', fullPageSpy);84          renderSpy(_.get($scope.spy, 'mode.name', null));85        });86      }87    };...

Full Screen

Full Screen

event_emitter_spec.js

Source:event_emitter_spec.js Github

copy

Full Screen

1describe('EventEmitter', function() {2  beforeEach(function() {3    this.spy = jasmine.createSpy();4    this.target = _.mixin({}, EventEmitter);5  });6  it('methods should be chainable', function() {7    expect(this.target.onSync()).toEqual(this.target);8    expect(this.target.onAsync()).toEqual(this.target);9    expect(this.target.off()).toEqual(this.target);10    expect(this.target.trigger()).toEqual(this.target);11  });12  it('#on should take the context a callback should be called in', function() {13    var context = { val: 3 }, cbContext;14    this.target.onSync('xevent', setCbContext, context).trigger('xevent');15    waitsFor(assertCbContext, 'callback was called in the wrong context');16    function setCbContext() { cbContext = this; }17    function assertCbContext() { return cbContext === context; }18  });19  it('#onAsync callbacks should be invoked asynchronously', function() {20    this.target.onAsync('event', this.spy).trigger('event');21    expect(this.spy.callCount).toBe(0);22    waitsFor(assertCallCount(this.spy, 1), 'the callback was not invoked');23  });24  it('#onSync callbacks should be invoked synchronously', function() {25    this.target.onSync('event', this.spy).trigger('event');26    expect(this.spy.callCount).toBe(1);27  });28  it('#off should remove callbacks', function() {29    this.target30    .onSync('event1 event2', this.spy)31    .onAsync('event1 event2', this.spy)32    .off('event1 event2')33    .trigger('event1 event2');34    waits(100);35    runs(assertCallCount(this.spy, 0));36  });37  it('methods should accept multiple event types', function() {38    this.target39    .onSync('event1 event2', this.spy)40    .onAsync('event1 event2', this.spy)41    .trigger('event1 event2');42    expect(this.spy.callCount).toBe(2);43    waitsFor(assertCallCount(this.spy, 4), 'the callback was not invoked');44  });45  it('the event type should be passed to the callback', function() {46    this.target47    .onSync('sync', this.spy)48    .onAsync('async', this.spy)49    .trigger('sync async');50    waitsFor(assertArgs(this.spy, 0, ['sync']), 'bad args');51    waitsFor(assertArgs(this.spy, 1, ['async']), 'bad args');52  });53  it('arbitrary args should be passed to the callback', function() {54    this.target55    .onSync('event', this.spy)56    .onAsync('event', this.spy)57    .trigger('event', 1, 2);58    waitsFor(assertArgs(this.spy, 0, ['event', 1, 2]), 'bad args');59    waitsFor(assertArgs(this.spy, 1, ['event', 1, 2]), 'bad args');60  });61  it('callback execution should be cancellable', function() {62    var cancelSpy = jasmine.createSpy().andCallFake(cancel);63    this.target64    .onSync('one', cancelSpy)65    .onSync('one', this.spy)66    .onAsync('two', cancelSpy)67    .onAsync('two', this.spy)68    .onSync('three', cancelSpy)69    .onAsync('three', this.spy)70    .trigger('one two three');71    waitsFor(assertCallCount(cancelSpy, 3));72    waitsFor(assertCallCount(this.spy, 0));73    function cancel() { return false; }74  });75  function assertCallCount(spy, expected) {76    return function() { return spy.callCount === expected; };77  }78  function assertArgs(spy, call, expected) {79    return function() {80      var env = jasmine.getEnv(),81          actual = spy.calls[call] ? spy.calls[call].args : undefined;82      return env.equals_(actual, expected);83    };84  }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('My First Test', function() {2  it('Does not do much!', function() {3    cy.contains('type').click()4    cy.url().should('include', '/commands/actions')5    cy.get('.action-email')6      .type('

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('My First Test', function() {2  it('Visits the Kitchen Sink', function() {3    cy.contains('type').click()4    cy.url().should('include', '/commands/actions')5    cy.get('.action-email')6      .type('

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('My First Test', function() {2  it('Does not do much!', function() {3    cy.pause()4    cy.contains('type').click()5    cy.url().should('include', '/commands/actions')6    cy.get('.action-email')7      .type('

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('My First Test', () => {2  it('Does not do much!', () => {3    expect(true).to.equal(true)4  })5  it('Does not do much!', () => {6    cy.contains('Login').click()7    cy.get('#username').type('test')8    cy.get('#password').type('test')9    cy.get('#login-button').click()10  })11  it('Does not do much!', () => {12    cy.contains('Login').click()13    cy.get('#username').type('test')14    cy.get('#password').type('test')15    cy.get('#login-button').click()16    cy.contains('Logout').click()17  })18  it('Does not do much!', () => {19    cy.contains('Login').click()20    cy.get('#username').type('test')21    cy.get('#password').type('test')22    cy.get('#login-button').click()23    cy.contains('Logout').click()24    cy.contains('Login').click()25  })26  it('Does not do much!', () => {27    cy.contains('Login').click()28    cy.get('#username').type('test')29    cy.get('#password').type('test')30    cy.get('#login-button').click()31    cy.contains('Logout').click()32    cy.contains('Login').click()33    cy.get('#username').type('test')34    cy.get('#password').type('test')35    cy.get('#login-button').click()36  })37  it('Does not do much!', () => {38    cy.contains('Login').click()39    cy.get('#username').type('test')40    cy.get('#password').type('test')41    cy.get('#login-button').click()42    cy.contains('Logout').click()43    cy.contains('Login').click()44    cy.get('#username').type('test')45    cy.get('#password').type('test')46    cy.get('#login-button').click()47    cy.contains('Logout').click()48  })49  it('Does not do much!', () => {50    cy.contains('Login').click()51    cy.get('#username').type('test')

Full Screen

Using AI Code Generation

copy

Full Screen

1cy.spy(object, 'method')2sinon.spy(object, 'method')3jest.spyOn(object, 'method')4spyOn(object, 'method')5sinon.spy(object, 'method')6sinon.spy(object, 'method')7sinon.spy(object, 'method')8sinon.spy(object, 'method')9sinon.spy(object, 'method')10sinon.spy(object, 'method')11sinon.spy(object, 'method')12sinon.spy(object, 'method')13sinon.spy(object, 'method')14sinon.spy(object, 'method')15sinon.spy(object, 'method')16sinon.spy(object, 'method')17sinon.spy(object, 'method')18sinon.spy(object, 'method')19sinon.spy(object, 'method')20sinon.spy(object, 'method')21sinon.spy(object, 'method')22sinon.spy(object, 'method')23sinon.spy(object, 'method')24sinon.spy(object, 'method')25sinon.spy(object, 'method')26sinon.spy(object, 'method')27sinon.spy(object, 'method')28sinon.spy(object, 'method')

Full Screen

Using AI Code Generation

copy

Full Screen

1it('should spy on a function', () => {2  const obj = { fn: () => {} }3  cy.spy(obj, 'fn').as('spy')4  cy.get('@spy').should('have.been.called')5})6it('should stub a function', () => {7  const obj = { fn: () => {} }8  cy.stub(obj, 'fn').as('stub')9  cy.get('@stub').should('have.been.called')10})11it('should stub a function', () => {12  const obj = { fn: () => {} }13  cy.clock().as('clock')14  cy.get('@clock').should('have.been.called')15})16it('should stub a function', () => {17  const obj = { fn: () => {} }18  cy.wait(1000).as('wait')19  cy.get('@wait').should('have.been.called')20})21it('should stub a function', () => {22  const obj = { fn: () => {} }23  cy.task('someTask').as('task')24  cy.get('@task').should('have.been.called')25})26it('should stub a function', () => {27  const obj = { fn: () => {} }28  cy.wrap(obj).as('wrap')29  cy.get('@wrap').should('have.been.called')30})31it('should stub a function', () => {32  const obj = { fn: () => {} }33  cy.request('www.google.com').as('request')34  cy.get('@request').should('have.been.called')35})36it('should stub a function', () => {37  const obj = { fn: () => {} }38  cy.debug().as('debug')39  cy.get('@debug').should('have.been.called')40})41it('should stub a function', () => {42  const obj = { fn: () => {} }43  cy.exec('ls -la').as('exec')44  cy.get('@exec').should('have.been.called')45})46it('should stub a function',

Full Screen

Using AI Code Generation

copy

Full Screen

1describe("my first test", () => {2  it("does not do much!", () => {3    expect(true).to.equal(true);4  });5  it("should visit the app", () => {6  });7  it("should visit the app", () => {8    cy.contains("Hello World");9  });10  it("should visit the app", () => {11    cy.contains("Hello World");12    cy.contains("Hello World").click();13  });14  it("should visit the app", () => {15    cy.contains("Hello World").click();16    cy.contains("Hello World").click();17  });18  it("should visit the app", () => {19    cy.contains("Hello World").click();20    cy.contains("Hello World").click();21    cy.contains("Hello World").click();22  });23  it("should visit the app", () => {24    cy.contains("Hello World").click();25    cy.contains("Hello World").click();26    cy.contains("Hello World").click();27    cy.contains("Hello World").click();28  });29  it("should visit the app", () => {30    cy.contains("Hello World").click();

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('test', function(){2    it('test', function(){3        cy.get('input[name="q"]').type('cypress');4        cy.get('input[name="btnK"]').click();5    })6})7describe('test', function(){8    it('test', function(){9        cy.get('input[name="q"]').type('cypress');10        cy.get('input[name="btnK"]').click();11        cy.wait('@cypress');12    })13})14describe('test', function(){15    it('test', function(){16        cy.get('input[name="q"]').type('cypress');17        cy.get('input[name="btnK"]').click();18        cy.wait('@cypress');19    })20})21describe('test', function(){22    it('test', function(){23        cy.server();24        cy.get('input[name="q"]').type('cypress');25        cy.get('input[name="btnK"]').click();26        cy.wait('@cypress');27    })28})29describe('test', function(){30    it('test', function(){31        cy.server();32        cy.get('input[name="q"]').type('cypress');33        cy.get('input[name="btnK"]').click();34        cy.wait('@cypress');35    })

Full Screen

Using AI Code Generation

copy

Full Screen

1it('should spy on a method', () => {2  const obj = {3    method: () => 'real return value'4  }5  cy.spy(obj, 'method').as('obj.method')6  obj.method()7  cy.get('@obj.method').should('have.been.called')8})9it('should stub a method', () => {10  const obj = {11    method: () => 'real return value'12  }13  cy.stub(obj, 'method').returns('stubbed return value')14  expect(obj.method()).to.equal('stubbed return value')15})16it('should wait for an element', () => {17  cy.get('#buttonSimple').click()18  cy.get('#buttonSimple').should('have.text', 'Changed')19})20it('should wait until a condition is true', () => {21  cy.get('#buttonDelay').click()22  cy.waitUntil(() => cy.get('#buttonDelay').should('have.text', 'Delayed Button'))23})24it('should use within', () => {25  cy.get('.query-list').within(() => {26    cy.get('li:first').should('contain', 'bananas')27    cy.get('li:last').should('contain', 'apples')28  })29})30it('should wrap an object', () => {31  const obj = { foo: 'bar' }32  cy.wrap(obj).should('have.property', 'foo').and('equal', 'bar')33})34it('should write to a file', () => {35  cy.writeFile('cypress/fixtures/example.json', { foo: 'bar' })36})

Full Screen

Using AI Code Generation

copy

Full Screen

1import React from 'react';2import { mount } from 'cypress-react-unit-test';3import Header from './header';4describe('Header', () => {5  it('calls login when login button is clicked', () => {6    const login = cy.spy();7    mount(<Header login={login} />);8    cy.contains('Login').click();9    expect(login).to.be.called;10  });11});12import React from 'react';13import { Button } from 'react-bootstrap';14const Header = ({ login }) => (15    <Button onClick={login}>Login</Button>16);17export default Header;18{19  "scripts": {20  },21  "devDependencies": {22  }23}24{25  "env": {26  }27}28describe('Header', () => {29  it('calls login when login button is clicked', () => {30    const login = cy.spy();31    cy.mount(<Header login={login} />);32    cy.contains('Login').click();33    expect(login).to.be.called;34  });35});

Full Screen

Cypress Tutorial

Cypress is a renowned Javascript-based open-source, easy-to-use end-to-end testing framework primarily used for testing web applications. Cypress is a relatively new player in the automation testing space and has been gaining much traction lately, as evidenced by the number of Forks (2.7K) and Stars (42.1K) for the project. LambdaTest’s Cypress Tutorial covers step-by-step guides that will help you learn from the basics till you run automation tests on LambdaTest.

Chapters:

  1. What is Cypress? -
  2. Why Cypress? - Learn why Cypress might be a good choice for testing your web applications.
  3. Features of Cypress Testing - Learn about features that make Cypress a powerful and flexible tool for testing web applications.
  4. Cypress Drawbacks - Although Cypress has many strengths, it has a few limitations that you should be aware of.
  5. Cypress Architecture - Learn more about Cypress architecture and how it is designed to be run directly in the browser, i.e., it does not have any additional servers.
  6. Browsers Supported by Cypress - Cypress is built on top of the Electron browser, supporting all modern web browsers. Learn browsers that support Cypress.
  7. Selenium vs Cypress: A Detailed Comparison - Compare and explore some key differences in terms of their design and features.
  8. Cypress Learning: Best Practices - Take a deep dive into some of the best practices you should use to avoid anti-patterns in your automation tests.
  9. How To Run Cypress Tests on LambdaTest? - Set up a LambdaTest account, and now you are all set to learn how to run Cypress tests.

Certification

You can elevate your expertise with end-to-end testing using the Cypress automation framework and stay one step ahead in your career by earning a Cypress certification. Check out our Cypress 101 Certification.

YouTube

Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.

Run Cypress automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful