How to use stub method in sinon

Best JavaScript code snippet using sinon

stub-test.js

Source:stub-test.js Github

copy

Full Screen

...28 assert.same(syncVersions, asyncVersions,29 "Stub prototype should contain same amount of synchronous and asynchronous methods");30 },31 "should allow overriding async behavior with sync behavior": function () {32 var stub = sinon.stub();33 var callback = sinon.spy();34 stub.callsArgAsync(1);35 stub.callsArg(1);36 stub(1, callback);37 assert(callback.called);38 },39 ".returns": {40 "returns specified value": function () {41 var stub = sinon.stub.create();42 var object = {};43 stub.returns(object);44 assert.same(stub(), object);45 },46 "returns should return stub": function () {47 var stub = sinon.stub.create();48 assert.same(stub.returns(""), stub);49 },50 "returns undefined": function () {51 var stub = sinon.stub.create();52 refute.defined(stub());53 },54 "supersedes previous throws": function () {55 var stub = sinon.stub.create();56 stub.throws().returns(1);57 refute.exception(function () {58 stub();59 });60 }61 },62 ".returnsArg": {63 "returns argument at specified index": function () {64 var stub = sinon.stub.create();65 stub.returnsArg(0);66 var object = {};67 assert.same(stub(object), object);68 },69 "returns stub": function () {70 var stub = sinon.stub.create();71 assert.same(stub.returnsArg(0), stub);72 },73 "throws if no index is specified": function () {74 var stub = sinon.stub.create();75 assert.exception(function () {76 stub.returnsArg();77 }, "TypeError");78 },79 "throws if index is not number": function () {80 var stub = sinon.stub.create();81 assert.exception(function () {82 stub.returnsArg({});83 }, "TypeError");84 }85 },86 ".returnsThis": {87 "stub returns this": function () {88 var instance = {};89 instance.stub = sinon.stub.create();90 instance.stub.returnsThis();91 assert.same(instance.stub(), instance);92 },93 "stub returns undefined when detached": {94 requiresSupportFor: {95 strictMode: (function () {96 return this;97 }()) === undefined98 },99 "": function () {100 var stub = sinon.stub.create();101 stub.returnsThis();102 // Due to strict mode, would be `global` otherwise103 assert.same(stub(), undefined);104 }105 },106 "stub respects call/apply": function () {107 var stub = sinon.stub.create();108 stub.returnsThis();109 var object = {};110 assert.same(stub.call(object), object);111 assert.same(stub.apply(object), object);112 },113 "returns stub": function () {114 var stub = sinon.stub.create();115 assert.same(stub.returnsThis(), stub);116 }117 },118 ".throws": {119 "throws specified exception": function () {120 var stub = sinon.stub.create();121 var error = new Error();122 stub.throws(error);123 try {124 stub();125 fail("Expected stub to throw");126 } catch (e) {127 assert.same(e, error);128 }129 },130 "returns stub": function () {131 var stub = sinon.stub.create();132 assert.same(stub.throws({}), stub);133 },134 "sets type of exception to throw": function () {135 var stub = sinon.stub.create();136 var exceptionType = "TypeError";137 stub.throws(exceptionType);138 assert.exception(function () {139 stub();140 }, exceptionType);141 },142 "specifies exception message": function () {143 var stub = sinon.stub.create();144 var message = "Oh no!";145 stub.throws("Error", message);146 try {147 stub();148 buster.referee.fail("Expected stub to throw");149 } catch (e) {150 assert.equals(e.message, message);151 }152 },153 "does not specify exception message if not provided": function () {154 var stub = sinon.stub.create();155 stub.throws("Error");156 try {157 stub();158 buster.referee.fail("Expected stub to throw");159 } catch (e) {160 assert.equals(e.message, "");161 }162 },163 "throws generic error": function () {164 var stub = sinon.stub.create();165 stub.throws();166 assert.exception(function () {167 stub();168 }, "Error");169 },170 "resets 'invoking' flag": function () {171 var stub = sinon.stub.create();172 stub.throws();173 try {174 stub();175 } catch (e) {176 refute.defined(stub.invoking);177 }178 }179 },180 ".callsArg": {181 setUp: function () {182 this.stub = sinon.stub.create();183 },184 "calls argument at specified index": function () {185 this.stub.callsArg(2);186 var callback = sinon.stub.create();187 this.stub(1, 2, callback);188 assert(callback.called);189 },190 "returns stub": function () {191 assert.isFunction(this.stub.callsArg(2));192 },193 "throws if argument at specified index is not callable": function () {194 this.stub.callsArg(0);195 assert.exception(function () {196 this.stub(1);197 }, "TypeError");198 },199 "throws if no index is specified": function () {200 var stub = this.stub;201 assert.exception(function () {202 stub.callsArg();203 }, "TypeError");204 },205 "throws if index is not number": function () {206 var stub = this.stub;207 assert.exception(function () {208 stub.callsArg({});209 }, "TypeError");210 }211 },212 ".callsArgWith": {213 setUp: function () {214 this.stub = sinon.stub.create();215 },216 "calls argument at specified index with provided args": function () {217 var object = {};218 this.stub.callsArgWith(1, object);219 var callback = sinon.stub.create();220 this.stub(1, callback);221 assert(callback.calledWith(object));222 },223 "returns function": function () {224 var stub = this.stub.callsArgWith(2, 3);225 assert.isFunction(stub);226 },227 "calls callback without args": function () {228 this.stub.callsArgWith(1);229 var callback = sinon.stub.create();230 this.stub(1, callback);231 assert(callback.calledWith());232 },233 "calls callback with multiple args": function () {234 var object = {};235 var array = [];236 this.stub.callsArgWith(1, object, array);237 var callback = sinon.stub.create();238 this.stub(1, callback);239 assert(callback.calledWith(object, array));240 },241 "throws if no index is specified": function () {242 var stub = this.stub;243 assert.exception(function () {244 stub.callsArgWith();245 }, "TypeError");246 },247 "throws if index is not number": function () {248 var stub = this.stub;249 assert.exception(function () {250 stub.callsArgWith({});251 }, "TypeError");252 }253 },254 ".callsArgOn": {255 setUp: function () {256 this.stub = sinon.stub.create();257 this.fakeContext = {258 foo: "bar"259 };260 },261 "calls argument at specified index": function () {262 this.stub.callsArgOn(2, this.fakeContext);263 var callback = sinon.stub.create();264 this.stub(1, 2, callback);265 assert(callback.called);266 assert(callback.calledOn(this.fakeContext));267 },268 "returns stub": function () {269 var stub = this.stub.callsArgOn(2, this.fakeContext);270 assert.isFunction(stub);271 },272 "throws if argument at specified index is not callable": function () {273 this.stub.callsArgOn(0, this.fakeContext);274 assert.exception(function () {275 this.stub(1);276 }, "TypeError");277 },278 "throws if no index is specified": function () {279 var stub = this.stub;280 assert.exception(function () {281 stub.callsArgOn();282 }, "TypeError");283 },284 "throws if no context is specified": function () {285 var stub = this.stub;286 assert.exception(function () {287 stub.callsArgOn(3);288 }, "TypeError");289 },290 "throws if index is not number": function () {291 var stub = this.stub;292 assert.exception(function () {293 stub.callsArgOn(this.fakeContext, 2);294 }, "TypeError");295 },296 "throws if context is not an object": function () {297 var stub = this.stub;298 assert.exception(function () {299 stub.callsArgOn(2, 2);300 }, "TypeError");301 }302 },303 ".callsArgOnWith": {304 setUp: function () {305 this.stub = sinon.stub.create();306 this.fakeContext = { foo: "bar" };307 },308 "calls argument at specified index with provided args": function () {309 var object = {};310 this.stub.callsArgOnWith(1, this.fakeContext, object);311 var callback = sinon.stub.create();312 this.stub(1, callback);313 assert(callback.calledWith(object));314 assert(callback.calledOn(this.fakeContext));315 },316 "returns function": function () {317 var stub = this.stub.callsArgOnWith(2, this.fakeContext, 3);318 assert.isFunction(stub);319 },320 "calls callback without args": function () {321 this.stub.callsArgOnWith(1, this.fakeContext);322 var callback = sinon.stub.create();323 this.stub(1, callback);324 assert(callback.calledWith());325 assert(callback.calledOn(this.fakeContext));326 },327 "calls callback with multiple args": function () {328 var object = {};329 var array = [];330 this.stub.callsArgOnWith(1, this.fakeContext, object, array);331 var callback = sinon.stub.create();332 this.stub(1, callback);333 assert(callback.calledWith(object, array));334 assert(callback.calledOn(this.fakeContext));335 },336 "throws if no index is specified": function () {337 var stub = this.stub;338 assert.exception(function () {339 stub.callsArgOnWith();340 }, "TypeError");341 },342 "throws if no context is specified": function () {343 var stub = this.stub;344 assert.exception(function () {345 stub.callsArgOnWith(3);346 }, "TypeError");347 },348 "throws if index is not number": function () {349 var stub = this.stub;350 assert.exception(function () {351 stub.callsArgOnWith({});352 }, "TypeError");353 },354 "throws if context is not an object": function () {355 var stub = this.stub;356 assert.exception(function () {357 stub.callsArgOnWith(2, 2);358 }, "TypeError");359 }360 },361 ".objectMethod": {362 setUp: function () {363 this.method = function () {};364 this.object = { method: this.method };365 this.wrapMethod = sinon.wrapMethod;366 },367 tearDown: function () {368 sinon.wrapMethod = this.wrapMethod;369 },370 "returns function from wrapMethod": function () {371 var wrapper = function () {};372 sinon.wrapMethod = function () {373 return wrapper;374 };375 var result = sinon.stub(this.object, "method");376 assert.same(result, wrapper);377 },378 "passes object and method to wrapMethod": function () {379 var wrapper = function () {};380 var args;381 sinon.wrapMethod = function () {382 args = arguments;383 return wrapper;384 };385 sinon.stub(this.object, "method");386 assert.same(args[0], this.object);387 assert.same(args[1], "method");388 },389 "uses provided function as stub": function () {390 var called = false;391 var stub = sinon.stub(this.object, "method", function () {392 called = true;393 });394 stub();395 assert(called);396 },397 "wraps provided function": function () {398 var customStub = function () {};399 var stub = sinon.stub(this.object, "method", customStub);400 refute.same(stub, customStub);401 assert.isFunction(stub.restore);402 },403 "throws if third argument is provided but not a function or proprety descriptor": function () {404 var object = this.object;405 assert.exception(function () {406 sinon.stub(object, "method", 1);407 }, "TypeError");408 },409 "stubbed method should be proper stub": function () {410 var stub = sinon.stub(this.object, "method");411 assert.isFunction(stub.returns);412 assert.isFunction(stub.throws);413 },414 "custom stubbed method should not be proper stub": function () {415 var stub = sinon.stub(this.object, "method", function () {});416 refute.defined(stub.returns);417 refute.defined(stub.throws);418 },419 "stub should be spy": function () {420 var stub = sinon.stub(this.object, "method");421 this.object.method();422 assert(stub.called);423 assert(stub.calledOn(this.object));424 },425 "custom stubbed method should be spy": function () {426 var stub = sinon.stub(this.object, "method", function () {});427 this.object.method();428 assert(stub.called);429 assert(stub.calledOn(this.object));430 },431 "stub should affect spy": function () {432 var stub = sinon.stub(this.object, "method");433 stub.throws("TypeError");434 try {435 this.object.method();436 }437 catch (e) {} // eslint-disable-line no-empty438 assert(stub.threw("TypeError"));439 },440 "returns standalone stub without arguments": function () {441 var stub = sinon.stub();442 assert.isFunction(stub);443 assert.isFalse(stub.called);444 },445 "throws if property is not a function": function () {446 var obj = { someProp: 42 };447 assert.exception(function () {448 sinon.stub(obj, "someProp");449 });450 assert.equals(obj.someProp, 42);451 },452 "successfully stubs falsey properties": function () {453 var obj = { 0: function () { } };454 sinon.stub(obj, 0, function () {455 return "stubbed value";456 });457 assert.equals(obj[0](), "stubbed value");458 },459 "does not stub function object": function () {460 assert.exception(function () {461 sinon.stub(function () {});462 });463 }464 },465 everything: {466 "stubs all methods of object without property": function () {467 var obj = {468 func1: function () {},469 func2: function () {},470 func3: function () {}471 };472 sinon.stub(obj);473 assert.isFunction(obj.func1.restore);474 assert.isFunction(obj.func2.restore);475 assert.isFunction(obj.func3.restore);476 },477 "stubs prototype methods": function () {478 function Obj() {}479 Obj.prototype.func1 = function () {};480 var obj = new Obj();481 sinon.stub(obj);482 assert.isFunction(obj.func1.restore);483 },484 "returns object": function () {485 var object = {};486 assert.same(sinon.stub(object), object);487 },488 "only stubs functions": function () {489 var object = { foo: "bar" };490 sinon.stub(object);491 assert.equals(object.foo, "bar");492 }493 },494 "stubbed function": {495 "throws if stubbing non-existent property": function () {496 var myObj = {};497 assert.exception(function () {498 sinon.stub(myObj, "ouch");499 });500 refute.defined(myObj.ouch);501 },502 "has toString method": function () {503 var obj = { meth: function () {} };504 sinon.stub(obj, "meth");505 assert.equals(obj.meth.toString(), "meth");506 },507 "toString should say 'stub' when unable to infer name": function () {508 var stub = sinon.stub();509 assert.equals(stub.toString(), "stub");510 },511 "toString should prefer property name if possible": function () {512 var obj = {};513 obj.meth = sinon.stub();514 obj.meth();515 assert.equals(obj.meth.toString(), "meth");516 }517 },518 ".yields": {519 "invokes only argument as callback": function () {520 var stub = sinon.stub().yields();521 var spy = sinon.spy();522 stub(spy);523 assert(spy.calledOnce);524 assert.equals(spy.args[0].length, 0);525 },526 "throws understandable error if no callback is passed": function () {527 var stub = sinon.stub().yields();528 try {529 stub();530 throw new Error();531 } catch (e) {532 assert.equals(e.message, "stub expected to yield, but no callback was passed.");533 }534 },535 "includes stub name and actual arguments in error": function () {536 var myObj = { somethingAwesome: function () {} };537 var stub = sinon.stub(myObj, "somethingAwesome").yields();538 try {539 stub(23, 42);540 throw new Error();541 } catch (e) {542 assert.equals(e.message, "somethingAwesome expected to yield, but no callback " +543 "was passed. Received [23, 42]");544 }545 },546 "invokes last argument as callback": function () {547 var stub = sinon.stub().yields();548 var spy = sinon.spy();549 stub(24, {}, spy);550 assert(spy.calledOnce);551 assert.equals(spy.args[0].length, 0);552 },553 "invokes first of two callbacks": function () {554 var stub = sinon.stub().yields();555 var spy = sinon.spy();556 var spy2 = sinon.spy();557 stub(24, {}, spy, spy2);558 assert(spy.calledOnce);559 assert(!spy2.called);560 },561 "invokes callback with arguments": function () {562 var obj = { id: 42 };563 var stub = sinon.stub().yields(obj, "Crazy");564 var spy = sinon.spy();565 stub(spy);566 assert(spy.calledWith(obj, "Crazy"));567 },568 "throws if callback throws": function () {569 var obj = { id: 42 };570 var stub = sinon.stub().yields(obj, "Crazy");571 var callback = sinon.stub().throws();572 assert.exception(function () {573 stub(callback);574 });575 },576 "plays nice with throws": function () {577 var stub = sinon.stub().throws().yields();578 var spy = sinon.spy();579 assert.exception(function () {580 stub(spy);581 });582 assert(spy.calledOnce);583 },584 "plays nice with returns": function () {585 var obj = {};586 var stub = sinon.stub().returns(obj).yields();587 var spy = sinon.spy();588 assert.same(stub(spy), obj);589 assert(spy.calledOnce);590 },591 "plays nice with returnsArg": function () {592 var stub = sinon.stub().returnsArg(0).yields();593 var spy = sinon.spy();594 assert.same(stub(spy), spy);595 assert(spy.calledOnce);596 },597 "plays nice with returnsThis": function () {598 var obj = {};599 var stub = sinon.stub().returnsThis().yields();600 var spy = sinon.spy();601 assert.same(stub.call(obj, spy), obj);602 assert(spy.calledOnce);603 }604 },605 ".yieldsRight": {606 "invokes only argument as callback": function () {607 var stub = sinon.stub().yieldsRight();608 var spy = sinon.spy();609 stub(spy);610 assert(spy.calledOnce);611 assert.equals(spy.args[0].length, 0);612 },613 "throws understandable error if no callback is passed": function () {614 var stub = sinon.stub().yieldsRight();615 try {616 stub();617 throw new Error();618 } catch (e) {619 assert.equals(e.message, "stub expected to yield, but no callback was passed.");620 }621 },622 "includes stub name and actual arguments in error": function () {623 var myObj = { somethingAwesome: function () {} };624 var stub = sinon.stub(myObj, "somethingAwesome").yieldsRight();625 try {626 stub(23, 42);627 throw new Error();628 } catch (e) {629 assert.equals(e.message, "somethingAwesome expected to yield, but no callback " +630 "was passed. Received [23, 42]");631 }632 },633 "invokes last argument as callback": function () {634 var stub = sinon.stub().yieldsRight();635 var spy = sinon.spy();636 stub(24, {}, spy);637 assert(spy.calledOnce);638 assert.equals(spy.args[0].length, 0);639 },640 "invokes the last of two callbacks": function () {641 var stub = sinon.stub().yieldsRight();642 var spy = sinon.spy();643 var spy2 = sinon.spy();644 stub(24, {}, spy, spy2);645 assert(!spy.called);646 assert(spy2.calledOnce);647 },648 "invokes callback with arguments": function () {649 var obj = { id: 42 };650 var stub = sinon.stub().yieldsRight(obj, "Crazy");651 var spy = sinon.spy();652 stub(spy);653 assert(spy.calledWith(obj, "Crazy"));654 },655 "throws if callback throws": function () {656 var obj = { id: 42 };657 var stub = sinon.stub().yieldsRight(obj, "Crazy");658 var callback = sinon.stub().throws();659 assert.exception(function () {660 stub(callback);661 });662 },663 "plays nice with throws": function () {664 var stub = sinon.stub().throws().yieldsRight();665 var spy = sinon.spy();666 assert.exception(function () {667 stub(spy);668 });669 assert(spy.calledOnce);670 },671 "plays nice with returns": function () {672 var obj = {};673 var stub = sinon.stub().returns(obj).yieldsRight();674 var spy = sinon.spy();675 assert.same(stub(spy), obj);676 assert(spy.calledOnce);677 },678 "plays nice with returnsArg": function () {679 var stub = sinon.stub().returnsArg(0).yieldsRight();680 var spy = sinon.spy();681 assert.same(stub(spy), spy);682 assert(spy.calledOnce);683 },684 "plays nice with returnsThis": function () {685 var obj = {};686 var stub = sinon.stub().returnsThis().yieldsRight();687 var spy = sinon.spy();688 assert.same(stub.call(obj, spy), obj);689 assert(spy.calledOnce);690 }691 },692 ".yieldsOn": {693 setUp: function () {694 this.stub = sinon.stub.create();695 this.fakeContext = { foo: "bar" };696 },697 "invokes only argument as callback": function () {698 var spy = sinon.spy();699 this.stub.yieldsOn(this.fakeContext);700 this.stub(spy);701 assert(spy.calledOnce);702 assert(spy.calledOn(this.fakeContext));703 assert.equals(spy.args[0].length, 0);704 },705 "throws if no context is specified": function () {706 assert.exception(function () {707 this.stub.yieldsOn();708 }, "TypeError");709 },710 "throws understandable error if no callback is passed": function () {711 this.stub.yieldsOn(this.fakeContext);712 try {713 this.stub();714 throw new Error();715 } catch (e) {716 assert.equals(e.message, "stub expected to yield, but no callback was passed.");717 }718 },719 "includes stub name and actual arguments in error": function () {720 var myObj = { somethingAwesome: function () {} };721 var stub = sinon.stub(myObj, "somethingAwesome").yieldsOn(this.fakeContext);722 try {723 stub(23, 42);724 throw new Error();725 } catch (e) {726 assert.equals(e.message, "somethingAwesome expected to yield, but no callback " +727 "was passed. Received [23, 42]");728 }729 },730 "invokes last argument as callback": function () {731 var spy = sinon.spy();732 this.stub.yieldsOn(this.fakeContext);733 this.stub(24, {}, spy);734 assert(spy.calledOnce);735 assert(spy.calledOn(this.fakeContext));736 assert.equals(spy.args[0].length, 0);737 },738 "invokes first of two callbacks": function () {739 var spy = sinon.spy();740 var spy2 = sinon.spy();741 this.stub.yieldsOn(this.fakeContext);742 this.stub(24, {}, spy, spy2);743 assert(spy.calledOnce);744 assert(spy.calledOn(this.fakeContext));745 assert(!spy2.called);746 },747 "invokes callback with arguments": function () {748 var obj = { id: 42 };749 var spy = sinon.spy();750 this.stub.yieldsOn(this.fakeContext, obj, "Crazy");751 this.stub(spy);752 assert(spy.calledWith(obj, "Crazy"));753 assert(spy.calledOn(this.fakeContext));754 },755 "throws if callback throws": function () {756 var obj = { id: 42 };757 var callback = sinon.stub().throws();758 this.stub.yieldsOn(this.fakeContext, obj, "Crazy");759 assert.exception(function () {760 this.stub(callback);761 });762 }763 },764 ".yieldsTo": {765 "yields to property of object argument": function () {766 var stub = sinon.stub().yieldsTo("success");767 var callback = sinon.spy();768 stub({ success: callback });769 assert(callback.calledOnce);770 assert.equals(callback.args[0].length, 0);771 },772 "throws understandable error if no object with callback is passed": function () {773 var stub = sinon.stub().yieldsTo("success");774 try {775 stub();776 throw new Error();777 } catch (e) {778 assert.equals(e.message, "stub expected to yield to 'success', but no object " +779 "with such a property was passed.");780 }781 },782 "includes stub name and actual arguments in error": function () {783 var myObj = { somethingAwesome: function () {} };784 var stub = sinon.stub(myObj, "somethingAwesome").yieldsTo("success");785 try {786 stub(23, 42);787 throw new Error();788 } catch (e) {789 assert.equals(e.message, "somethingAwesome expected to yield to 'success', but " +790 "no object with such a property was passed. " +791 "Received [23, 42]");792 }793 },794 "invokes property on last argument as callback": function () {795 var stub = sinon.stub().yieldsTo("success");796 var callback = sinon.spy();797 stub(24, {}, { success: callback });798 assert(callback.calledOnce);799 assert.equals(callback.args[0].length, 0);800 },801 "invokes first of two possible callbacks": function () {802 var stub = sinon.stub().yieldsTo("error");803 var callback = sinon.spy();804 var callback2 = sinon.spy();805 stub(24, {}, { error: callback }, { error: callback2 });806 assert(callback.calledOnce);807 assert(!callback2.called);808 },809 "invokes callback with arguments": function () {810 var obj = { id: 42 };811 var stub = sinon.stub().yieldsTo("success", obj, "Crazy");812 var callback = sinon.spy();813 stub({ success: callback });814 assert(callback.calledWith(obj, "Crazy"));815 },816 "throws if callback throws": function () {817 var obj = { id: 42 };818 var stub = sinon.stub().yieldsTo("error", obj, "Crazy");819 var callback = sinon.stub().throws();820 assert.exception(function () {821 stub({ error: callback });822 });823 }824 },825 ".yieldsToOn": {826 setUp: function () {827 this.stub = sinon.stub.create();828 this.fakeContext = { foo: "bar" };829 },830 "yields to property of object argument": function () {831 this.stub.yieldsToOn("success", this.fakeContext);832 var callback = sinon.spy();833 this.stub({ success: callback });834 assert(callback.calledOnce);835 assert(callback.calledOn(this.fakeContext));836 assert.equals(callback.args[0].length, 0);837 },838 "throws if no context is specified": function () {839 assert.exception(function () {840 this.stub.yieldsToOn("success");841 }, "TypeError");842 },843 "throws understandable error if no object with callback is passed": function () {844 this.stub.yieldsToOn("success", this.fakeContext);845 try {846 this.stub();847 throw new Error();848 } catch (e) {849 assert.equals(e.message, "stub expected to yield to 'success', but no object " +850 "with such a property was passed.");851 }852 },853 "includes stub name and actual arguments in error": function () {854 var myObj = { somethingAwesome: function () {} };855 var stub = sinon.stub(myObj, "somethingAwesome").yieldsToOn("success", this.fakeContext);856 try {857 stub(23, 42);858 throw new Error();859 } catch (e) {860 assert.equals(e.message, "somethingAwesome expected to yield to 'success', but " +861 "no object with such a property was passed. " +862 "Received [23, 42]");863 }864 },865 "invokes property on last argument as callback": function () {866 var callback = sinon.spy();867 this.stub.yieldsToOn("success", this.fakeContext);868 this.stub(24, {}, { success: callback });869 assert(callback.calledOnce);870 assert(callback.calledOn(this.fakeContext));871 assert.equals(callback.args[0].length, 0);872 },873 "invokes first of two possible callbacks": function () {874 var callback = sinon.spy();875 var callback2 = sinon.spy();876 this.stub.yieldsToOn("error", this.fakeContext);877 this.stub(24, {}, { error: callback }, { error: callback2 });878 assert(callback.calledOnce);879 assert(callback.calledOn(this.fakeContext));880 assert(!callback2.called);881 },882 "invokes callback with arguments": function () {883 var obj = { id: 42 };884 var callback = sinon.spy();885 this.stub.yieldsToOn("success", this.fakeContext, obj, "Crazy");886 this.stub({ success: callback });887 assert(callback.calledOn(this.fakeContext));888 assert(callback.calledWith(obj, "Crazy"));889 },890 "throws if callback throws": function () {891 var obj = { id: 42 };892 var callback = sinon.stub().throws();893 this.stub.yieldsToOn("error", this.fakeContext, obj, "Crazy");894 assert.exception(function () {895 this.stub({ error: callback });896 });897 }898 },899 ".withArgs": {900 "defines withArgs method": function () {901 var stub = sinon.stub();902 assert.isFunction(stub.withArgs);903 },904 "creates filtered stub": function () {905 var stub = sinon.stub();906 var other = stub.withArgs(23);907 refute.same(other, stub);908 assert.isFunction(stub.returns);909 assert.isFunction(other.returns);910 },911 "filters return values based on arguments": function () {912 var stub = sinon.stub().returns(23);913 stub.withArgs(42).returns(99);914 assert.equals(stub(), 23);915 assert.equals(stub(42), 99);916 },917 "filters exceptions based on arguments": function () {918 var stub = sinon.stub().returns(23);919 stub.withArgs(42).throws();920 refute.exception(stub);921 assert.exception(function () {922 stub(42);923 });924 }925 },926 ".callsArgAsync": {927 setUp: function () {928 this.stub = sinon.stub.create();929 },930 "asynchronously calls argument at specified index": function (done) {931 this.stub.callsArgAsync(2);932 var callback = sinon.spy(done);933 this.stub(1, 2, callback);934 assert(!callback.called);935 }936 },937 ".callsArgWithAsync": {938 setUp: function () {939 this.stub = sinon.stub.create();940 },941 "asynchronously calls callback at specified index with multiple args": function (done) {942 var object = {};943 var array = [];944 this.stub.callsArgWithAsync(1, object, array);945 var callback = sinon.spy(done(function () {946 assert(callback.calledWith(object, array));947 }));948 this.stub(1, callback);949 assert(!callback.called);950 }951 },952 ".callsArgOnAsync": {953 setUp: function () {954 this.stub = sinon.stub.create();955 this.fakeContext = {956 foo: "bar"957 };958 },959 "asynchronously calls argument at specified index with specified context": function (done) {960 var context = this.fakeContext;961 this.stub.callsArgOnAsync(2, context);962 var callback = sinon.spy(done(function () {963 assert(callback.calledOn(context));964 }));965 this.stub(1, 2, callback);966 assert(!callback.called);967 }968 },969 ".callsArgOnWithAsync": {970 setUp: function () {971 this.stub = sinon.stub.create();972 this.fakeContext = { foo: "bar" };973 },974 "asynchronously calls argument at specified index with provided context and args": function (done) {975 var object = {};976 var context = this.fakeContext;977 this.stub.callsArgOnWithAsync(1, context, object);978 var callback = sinon.spy(done(function () {979 assert(callback.calledOn(context));980 assert(callback.calledWith(object));981 }));982 this.stub(1, callback);983 assert(!callback.called);984 }985 },986 ".yieldsAsync": {987 "asynchronously invokes only argument as callback": function (done) {988 var stub = sinon.stub().yieldsAsync();989 var spy = sinon.spy(done);990 stub(spy);991 assert(!spy.called);992 }993 },994 ".yieldsOnAsync": {995 setUp: function () {996 this.stub = sinon.stub.create();997 this.fakeContext = { foo: "bar" };998 },999 "asynchronously invokes only argument as callback with given context": function (done) {1000 var context = this.fakeContext;1001 this.stub.yieldsOnAsync(context);1002 var spy = sinon.spy(done(function () {1003 assert(spy.calledOnce);1004 assert(spy.calledOn(context));1005 assert.equals(spy.args[0].length, 0);1006 }));1007 this.stub(spy);1008 assert(!spy.called);1009 }1010 },1011 ".yieldsToAsync": {1012 "asynchronously yields to property of object argument": function (done) {1013 var stub = sinon.stub().yieldsToAsync("success");1014 var callback = sinon.spy(done(function () {1015 assert(callback.calledOnce);1016 assert.equals(callback.args[0].length, 0);1017 }));1018 stub({ success: callback });1019 assert(!callback.called);1020 }1021 },1022 ".yieldsToOnAsync": {1023 setUp: function () {1024 this.stub = sinon.stub.create();1025 this.fakeContext = { foo: "bar" };1026 },1027 "asynchronously yields to property of object argument with given context": function (done) {1028 var context = this.fakeContext;1029 this.stub.yieldsToOnAsync("success", context);1030 var callback = sinon.spy(done(function () {1031 assert(callback.calledOnce);1032 assert(callback.calledOn(context));1033 assert.equals(callback.args[0].length, 0);1034 }));1035 this.stub({ success: callback });1036 assert(!callback.called);1037 }1038 },1039 ".onCall": {1040 "can be used with returns to produce sequence": function () {1041 var stub = sinon.stub().returns(3);1042 stub.onFirstCall().returns(1)1043 .onCall(2).returns(2);1044 assert.same(stub(), 1);1045 assert.same(stub(), 3);1046 assert.same(stub(), 2);1047 assert.same(stub(), 3);1048 },1049 "can be used with returnsArg to produce sequence": function () {1050 var stub = sinon.stub().returns("default");1051 stub.onSecondCall().returnsArg(0);1052 assert.same(stub(1), "default");1053 assert.same(stub(2), 2);1054 assert.same(stub(3), "default");1055 },1056 "can be used with returnsThis to produce sequence": function () {1057 var instance = {};1058 instance.stub = sinon.stub().returns("default");1059 instance.stub.onSecondCall().returnsThis();1060 assert.same(instance.stub(), "default");1061 assert.same(instance.stub(), instance);1062 assert.same(instance.stub(), "default");1063 },1064 "can be used with throwsException to produce sequence": function () {1065 var stub = sinon.stub();1066 var error = new Error();1067 stub.onSecondCall().throwsException(error);1068 stub();1069 try {1070 stub();1071 fail("Expected stub to throw");1072 } catch (e) {1073 assert.same(e, error);1074 }1075 },1076 "in combination with withArgs": {1077 "can produce a sequence for a fake": function () {1078 var stub = sinon.stub().returns(0);1079 stub.withArgs(5).returns(-1)1080 .onFirstCall().returns(1)1081 .onSecondCall().returns(2);1082 assert.same(stub(0), 0);1083 assert.same(stub(5), 1);1084 assert.same(stub(0), 0);1085 assert.same(stub(5), 2);1086 assert.same(stub(5), -1);1087 },1088 "falls back to stub default behaviour if fake does not have its own default behaviour": function () {1089 var stub = sinon.stub().returns(0);1090 stub.withArgs(5)1091 .onFirstCall().returns(1);1092 assert.same(stub(5), 1);1093 assert.same(stub(5), 0);1094 },1095 "falls back to stub behaviour for call if fake does not have its own behaviour for call": function () {1096 var stub = sinon.stub().returns(0);1097 stub.withArgs(5).onFirstCall().returns(1);1098 stub.onSecondCall().returns(2);1099 assert.same(stub(5), 1);1100 assert.same(stub(5), 2);1101 assert.same(stub(4), 0);1102 },1103 "defaults to undefined behaviour once no more calls have been defined": function () {1104 var stub = sinon.stub();1105 stub.withArgs(5).onFirstCall().returns(1)1106 .onSecondCall().returns(2);1107 assert.same(stub(5), 1);1108 assert.same(stub(5), 2);1109 refute.defined(stub(5));1110 },1111 "does not create undefined behaviour just by calling onCall": function () {1112 var stub = sinon.stub().returns(2);1113 stub.onFirstCall();1114 assert.same(stub(6), 2);1115 },1116 "works with fakes and reset": function () {1117 var stub = sinon.stub();1118 stub.withArgs(5).onFirstCall().returns(1);1119 stub.withArgs(5).onSecondCall().returns(2);1120 assert.same(stub(5), 1);1121 assert.same(stub(5), 2);1122 refute.defined(stub(5));1123 stub.reset();1124 assert.same(stub(5), 1);1125 assert.same(stub(5), 2);1126 refute.defined(stub(5));1127 },1128 "throws an understandable error when trying to use withArgs on behavior": function () {1129 try {1130 sinon.stub().onFirstCall().withArgs(1);1131 } catch (e) {1132 assert.match(e.message, /not supported/);1133 }1134 }1135 },1136 "can be used with yields* to produce a sequence": function () {1137 var context = { foo: "bar" };1138 var obj = { method1: sinon.spy(), method2: sinon.spy() };1139 var obj2 = { method2: sinon.spy() };1140 var stub = sinon.stub().yieldsToOn("method2", context, 7, 8);1141 stub.onFirstCall().yields(1, 2)1142 .onSecondCall().yieldsOn(context, 3, 4)1143 .onThirdCall().yieldsTo("method1", 5, 6)1144 .onCall(3).yieldsToOn("method2", context, 7, 8);1145 var spy1 = sinon.spy();1146 var spy2 = sinon.spy();1147 stub(spy1);1148 stub(spy2);1149 stub(obj);1150 stub(obj);1151 stub(obj2); // should continue with default behavior1152 assert(spy1.calledOnce);1153 assert(spy1.calledWithExactly(1, 2));1154 assert(spy2.calledOnce);1155 assert(spy2.calledAfter(spy1));1156 assert(spy2.calledOn(context));1157 assert(spy2.calledWithExactly(3, 4));1158 assert(obj.method1.calledOnce);1159 assert(obj.method1.calledAfter(spy2));1160 assert(obj.method1.calledWithExactly(5, 6));1161 assert(obj.method2.calledOnce);1162 assert(obj.method2.calledAfter(obj.method1));1163 assert(obj.method2.calledOn(context));1164 assert(obj.method2.calledWithExactly(7, 8));1165 assert(obj2.method2.calledOnce);1166 assert(obj2.method2.calledAfter(obj.method2));1167 assert(obj2.method2.calledOn(context));1168 assert(obj2.method2.calledWithExactly(7, 8));1169 },1170 "can be used with callsArg* to produce a sequence": function () {1171 var spy1 = sinon.spy();1172 var spy2 = sinon.spy();1173 var spy3 = sinon.spy();1174 var spy4 = sinon.spy();1175 var spy5 = sinon.spy();1176 var decoy = sinon.spy();1177 var context = { foo: "bar" };1178 var stub = sinon.stub().callsArgOnWith(3, context, "c", "d");1179 stub.onFirstCall().callsArg(0)1180 .onSecondCall().callsArgWith(1, "a", "b")1181 .onThirdCall().callsArgOn(2, context)1182 .onCall(3).callsArgOnWith(3, context, "c", "d");1183 stub(spy1);1184 stub(decoy, spy2);1185 stub(decoy, decoy, spy3);1186 stub(decoy, decoy, decoy, spy4);1187 stub(decoy, decoy, decoy, spy5); // should continue with default behavior1188 assert(spy1.calledOnce);1189 assert(spy2.calledOnce);1190 assert(spy2.calledAfter(spy1));1191 assert(spy2.calledWithExactly("a", "b"));1192 assert(spy3.calledOnce);1193 assert(spy3.calledAfter(spy2));1194 assert(spy3.calledOn(context));1195 assert(spy4.calledOnce);1196 assert(spy4.calledAfter(spy3));1197 assert(spy4.calledOn(context));1198 assert(spy4.calledWithExactly("c", "d"));1199 assert(spy5.calledOnce);1200 assert(spy5.calledAfter(spy4));1201 assert(spy5.calledOn(context));1202 assert(spy5.calledWithExactly("c", "d"));1203 assert(decoy.notCalled);1204 },1205 "can be used with yields* and callsArg* in combination to produce a sequence": function () {1206 var stub = sinon.stub().yields(1, 2);1207 stub.onSecondCall().callsArg(1)1208 .onThirdCall().yieldsTo("method")1209 .onCall(3).callsArgWith(2, "a", "b");1210 var obj = { method: sinon.spy() };1211 var spy1 = sinon.spy();1212 var spy2 = sinon.spy();1213 var spy3 = sinon.spy();1214 var decoy = sinon.spy();1215 stub(spy1);1216 stub(decoy, spy2);1217 stub(obj);1218 stub(decoy, decoy, spy3);1219 assert(spy1.calledOnce);1220 assert(spy2.calledOnce);1221 assert(spy2.calledAfter(spy1));1222 assert(obj.method.calledOnce);1223 assert(obj.method.calledAfter(spy2));1224 assert(spy3.calledOnce);1225 assert(spy3.calledAfter(obj.method));1226 assert(spy3.calledWithExactly("a", "b"));1227 assert(decoy.notCalled);1228 },1229 "should interact correctly with assertions (GH-231)": function () {1230 var stub = sinon.stub();1231 var spy = sinon.spy();1232 stub.callsArgWith(0, "a");1233 stub(spy);1234 assert(spy.calledWith("a"));1235 stub(spy);1236 assert(spy.calledWith("a"));1237 stub.onThirdCall().callsArgWith(0, "b");1238 stub(spy);1239 assert(spy.calledWith("b"));1240 }1241 },1242 "reset only resets call history": function () {1243 var obj = { a: function () {} };1244 var spy = sinon.spy();1245 sinon.stub(obj, "a").callsArg(1);1246 obj.a(null, spy);1247 obj.a.reset();1248 obj.a(null, spy);1249 assert(spy.calledTwice);1250 },1251 ".resetBehavior": {1252 "clears yields* and callsArg* sequence": function () {1253 var stub = sinon.stub().yields(1);1254 stub.onFirstCall().callsArg(1);1255 stub.resetBehavior();1256 stub.yields(3);1257 var spyWanted = sinon.spy();1258 var spyNotWanted = sinon.spy();1259 stub(spyWanted, spyNotWanted);1260 assert(spyNotWanted.notCalled);1261 assert(spyWanted.calledOnce);1262 assert(spyWanted.calledWithExactly(3));1263 },1264 "cleans 'returns' behavior": function () {1265 var stub = sinon.stub().returns(1);1266 stub.resetBehavior();1267 refute.defined(stub());1268 },1269 "cleans behavior of fakes returned by withArgs": function () {1270 var stub = sinon.stub();1271 stub.withArgs("lolz").returns(2);1272 stub.resetBehavior();1273 refute.defined(stub("lolz"));1274 },1275 "does not clean parents' behavior when called on a fake returned by withArgs": function () {1276 var parentStub = sinon.stub().returns(false);1277 var childStub = parentStub.withArgs("lolz").returns(true);1278 childStub.resetBehavior();1279 assert.same(parentStub("lolz"), false);1280 assert.same(parentStub(), false);1281 },1282 "cleans 'returnsArg' behavior": function () {1283 var stub = sinon.stub().returnsArg(0);1284 stub.resetBehavior();1285 refute.defined(stub("defined"));1286 },1287 "cleans 'returnsThis' behavior": function () {1288 var instance = {};1289 instance.stub = sinon.stub.create();1290 instance.stub.returnsThis();1291 instance.stub.resetBehavior();1292 refute.defined(instance.stub());1293 },1294 "does not touch properties that are reset by 'reset'": {1295 ".calledOnce": function () {1296 var stub = sinon.stub();1297 stub(1);1298 stub.resetBehavior();1299 assert(stub.calledOnce);1300 },1301 "called multiple times": function () {1302 var stub = sinon.stub();1303 stub(1);1304 stub(2);1305 stub(3);1306 stub.resetBehavior();1307 assert(stub.called);1308 assert.equals(stub.args.length, 3);1309 assert.equals(stub.returnValues.length, 3);1310 assert.equals(stub.exceptions.length, 3);1311 assert.equals(stub.thisValues.length, 3);1312 assert.defined(stub.firstCall);1313 assert.defined(stub.secondCall);1314 assert.defined(stub.thirdCall);1315 assert.defined(stub.lastCall);1316 },1317 "call order state": function () {1318 var stubs = [sinon.stub(), sinon.stub()];1319 stubs[0]();1320 stubs[1]();1321 stubs[0].resetBehavior();1322 assert(stubs[0].calledBefore(stubs[1]));1323 },1324 "fakes returned by withArgs": function () {1325 var stub = sinon.stub();1326 var fakeA = stub.withArgs("a");1327 var fakeB = stub.withArgs("b");1328 stub("a");1329 stub("b");1330 stub("c");1331 var fakeC = stub.withArgs("c");1332 stub.resetBehavior();1333 assert(fakeA.calledOnce);1334 assert(fakeB.calledOnce);1335 assert(fakeC.calledOnce);1336 }1337 }1338 },1339 ".length": {1340 "is zero by default": function () {1341 var stub = sinon.stub();1342 assert.equals(stub.length, 0);1343 },1344 "matches the function length": function () {1345 var api = { someMethod: function (a, b, c) {} }; // eslint-disable-line no-unused-vars1346 var stub = sinon.stub(api, "someMethod");1347 assert.equals(stub.length, 3);1348 }1349 }1350 });...

Full Screen

Full Screen

stub-test.7ea71d6d0d12.js

Source:stub-test.7ea71d6d0d12.js Github

copy

Full Screen

...28 assert.same(syncVersions, asyncVersions,29 "Stub prototype should contain same amount of synchronous and asynchronous methods");30 },31 "should allow overriding async behavior with sync behavior": function () {32 var stub = sinon.stub();33 var callback = sinon.spy();34 stub.callsArgAsync(1);35 stub.callsArg(1);36 stub(1, callback);37 assert(callback.called);38 },39 ".returns": {40 "returns specified value": function () {41 var stub = sinon.stub.create();42 var object = {};43 stub.returns(object);44 assert.same(stub(), object);45 },46 "returns should return stub": function () {47 var stub = sinon.stub.create();48 assert.same(stub.returns(""), stub);49 },50 "returns undefined": function () {51 var stub = sinon.stub.create();52 refute.defined(stub());53 },54 "supersedes previous throws": function () {55 var stub = sinon.stub.create();56 stub.throws().returns(1);57 refute.exception(function () {58 stub();59 });60 }61 },62 ".returnsArg": {63 "returns argument at specified index": function () {64 var stub = sinon.stub.create();65 stub.returnsArg(0);66 var object = {};67 assert.same(stub(object), object);68 },69 "returns stub": function () {70 var stub = sinon.stub.create();71 assert.same(stub.returnsArg(0), stub);72 },73 "throws if no index is specified": function () {74 var stub = sinon.stub.create();75 assert.exception(function () {76 stub.returnsArg();77 }, "TypeError");78 },79 "throws if index is not number": function () {80 var stub = sinon.stub.create();81 assert.exception(function () {82 stub.returnsArg({});83 }, "TypeError");84 }85 },86 ".returnsThis": {87 "stub returns this": function () {88 var instance = {};89 instance.stub = sinon.stub.create();90 instance.stub.returnsThis();91 assert.same(instance.stub(), instance);92 },93 "stub returns undefined when detached": {94 requiresSupportFor: {95 strictMode: (function () {96 return this;97 }()) === undefined98 },99 "": function () {100 var stub = sinon.stub.create();101 stub.returnsThis();102 // Due to strict mode, would be `global` otherwise103 assert.same(stub(), undefined);104 }105 },106 "stub respects call/apply": function () {107 var stub = sinon.stub.create();108 stub.returnsThis();109 var object = {};110 assert.same(stub.call(object), object);111 assert.same(stub.apply(object), object);112 },113 "returns stub": function () {114 var stub = sinon.stub.create();115 assert.same(stub.returnsThis(), stub);116 }117 },118 ".throws": {119 "throws specified exception": function () {120 var stub = sinon.stub.create();121 var error = new Error();122 stub.throws(error);123 try {124 stub();125 fail("Expected stub to throw");126 } catch (e) {127 assert.same(e, error);128 }129 },130 "returns stub": function () {131 var stub = sinon.stub.create();132 assert.same(stub.throws({}), stub);133 },134 "sets type of exception to throw": function () {135 var stub = sinon.stub.create();136 var exceptionType = "TypeError";137 stub.throws(exceptionType);138 assert.exception(function () {139 stub();140 }, exceptionType);141 },142 "specifies exception message": function () {143 var stub = sinon.stub.create();144 var message = "Oh no!";145 stub.throws("Error", message);146 try {147 stub();148 buster.referee.fail("Expected stub to throw");149 } catch (e) {150 assert.equals(e.message, message);151 }152 },153 "does not specify exception message if not provided": function () {154 var stub = sinon.stub.create();155 stub.throws("Error");156 try {157 stub();158 buster.referee.fail("Expected stub to throw");159 } catch (e) {160 assert.equals(e.message, "");161 }162 },163 "throws generic error": function () {164 var stub = sinon.stub.create();165 stub.throws();166 assert.exception(function () {167 stub();168 }, "Error");169 },170 "resets 'invoking' flag": function () {171 var stub = sinon.stub.create();172 stub.throws();173 try {174 stub();175 } catch (e) {176 refute.defined(stub.invoking);177 }178 }179 },180 ".callsArg": {181 setUp: function () {182 this.stub = sinon.stub.create();183 },184 "calls argument at specified index": function () {185 this.stub.callsArg(2);186 var callback = sinon.stub.create();187 this.stub(1, 2, callback);188 assert(callback.called);189 },190 "returns stub": function () {191 assert.isFunction(this.stub.callsArg(2));192 },193 "throws if argument at specified index is not callable": function () {194 this.stub.callsArg(0);195 assert.exception(function () {196 this.stub(1);197 }, "TypeError");198 },199 "throws if no index is specified": function () {200 var stub = this.stub;201 assert.exception(function () {202 stub.callsArg();203 }, "TypeError");204 },205 "throws if index is not number": function () {206 var stub = this.stub;207 assert.exception(function () {208 stub.callsArg({});209 }, "TypeError");210 }211 },212 ".callsArgWith": {213 setUp: function () {214 this.stub = sinon.stub.create();215 },216 "calls argument at specified index with provided args": function () {217 var object = {};218 this.stub.callsArgWith(1, object);219 var callback = sinon.stub.create();220 this.stub(1, callback);221 assert(callback.calledWith(object));222 },223 "returns function": function () {224 var stub = this.stub.callsArgWith(2, 3);225 assert.isFunction(stub);226 },227 "calls callback without args": function () {228 this.stub.callsArgWith(1);229 var callback = sinon.stub.create();230 this.stub(1, callback);231 assert(callback.calledWith());232 },233 "calls callback with multiple args": function () {234 var object = {};235 var array = [];236 this.stub.callsArgWith(1, object, array);237 var callback = sinon.stub.create();238 this.stub(1, callback);239 assert(callback.calledWith(object, array));240 },241 "throws if no index is specified": function () {242 var stub = this.stub;243 assert.exception(function () {244 stub.callsArgWith();245 }, "TypeError");246 },247 "throws if index is not number": function () {248 var stub = this.stub;249 assert.exception(function () {250 stub.callsArgWith({});251 }, "TypeError");252 }253 },254 ".callsArgOn": {255 setUp: function () {256 this.stub = sinon.stub.create();257 this.fakeContext = {258 foo: "bar"259 };260 },261 "calls argument at specified index": function () {262 this.stub.callsArgOn(2, this.fakeContext);263 var callback = sinon.stub.create();264 this.stub(1, 2, callback);265 assert(callback.called);266 assert(callback.calledOn(this.fakeContext));267 },268 "returns stub": function () {269 var stub = this.stub.callsArgOn(2, this.fakeContext);270 assert.isFunction(stub);271 },272 "throws if argument at specified index is not callable": function () {273 this.stub.callsArgOn(0, this.fakeContext);274 assert.exception(function () {275 this.stub(1);276 }, "TypeError");277 },278 "throws if no index is specified": function () {279 var stub = this.stub;280 assert.exception(function () {281 stub.callsArgOn();282 }, "TypeError");283 },284 "throws if no context is specified": function () {285 var stub = this.stub;286 assert.exception(function () {287 stub.callsArgOn(3);288 }, "TypeError");289 },290 "throws if index is not number": function () {291 var stub = this.stub;292 assert.exception(function () {293 stub.callsArgOn(this.fakeContext, 2);294 }, "TypeError");295 },296 "throws if context is not an object": function () {297 var stub = this.stub;298 assert.exception(function () {299 stub.callsArgOn(2, 2);300 }, "TypeError");301 }302 },303 ".callsArgOnWith": {304 setUp: function () {305 this.stub = sinon.stub.create();306 this.fakeContext = { foo: "bar" };307 },308 "calls argument at specified index with provided args": function () {309 var object = {};310 this.stub.callsArgOnWith(1, this.fakeContext, object);311 var callback = sinon.stub.create();312 this.stub(1, callback);313 assert(callback.calledWith(object));314 assert(callback.calledOn(this.fakeContext));315 },316 "returns function": function () {317 var stub = this.stub.callsArgOnWith(2, this.fakeContext, 3);318 assert.isFunction(stub);319 },320 "calls callback without args": function () {321 this.stub.callsArgOnWith(1, this.fakeContext);322 var callback = sinon.stub.create();323 this.stub(1, callback);324 assert(callback.calledWith());325 assert(callback.calledOn(this.fakeContext));326 },327 "calls callback with multiple args": function () {328 var object = {};329 var array = [];330 this.stub.callsArgOnWith(1, this.fakeContext, object, array);331 var callback = sinon.stub.create();332 this.stub(1, callback);333 assert(callback.calledWith(object, array));334 assert(callback.calledOn(this.fakeContext));335 },336 "throws if no index is specified": function () {337 var stub = this.stub;338 assert.exception(function () {339 stub.callsArgOnWith();340 }, "TypeError");341 },342 "throws if no context is specified": function () {343 var stub = this.stub;344 assert.exception(function () {345 stub.callsArgOnWith(3);346 }, "TypeError");347 },348 "throws if index is not number": function () {349 var stub = this.stub;350 assert.exception(function () {351 stub.callsArgOnWith({});352 }, "TypeError");353 },354 "throws if context is not an object": function () {355 var stub = this.stub;356 assert.exception(function () {357 stub.callsArgOnWith(2, 2);358 }, "TypeError");359 }360 },361 ".objectMethod": {362 setUp: function () {363 this.method = function () {};364 this.object = { method: this.method };365 this.wrapMethod = sinon.wrapMethod;366 },367 tearDown: function () {368 sinon.wrapMethod = this.wrapMethod;369 },370 "returns function from wrapMethod": function () {371 var wrapper = function () {};372 sinon.wrapMethod = function () {373 return wrapper;374 };375 var result = sinon.stub(this.object, "method");376 assert.same(result, wrapper);377 },378 "passes object and method to wrapMethod": function () {379 var wrapper = function () {};380 var args;381 sinon.wrapMethod = function () {382 args = arguments;383 return wrapper;384 };385 sinon.stub(this.object, "method");386 assert.same(args[0], this.object);387 assert.same(args[1], "method");388 },389 "uses provided function as stub": function () {390 var called = false;391 var stub = sinon.stub(this.object, "method", function () {392 called = true;393 });394 stub();395 assert(called);396 },397 "wraps provided function": function () {398 var customStub = function () {};399 var stub = sinon.stub(this.object, "method", customStub);400 refute.same(stub, customStub);401 assert.isFunction(stub.restore);402 },403 "throws if third argument is provided but not a function or proprety descriptor": function () {404 var object = this.object;405 assert.exception(function () {406 sinon.stub(object, "method", 1);407 }, "TypeError");408 },409 "stubbed method should be proper stub": function () {410 var stub = sinon.stub(this.object, "method");411 assert.isFunction(stub.returns);412 assert.isFunction(stub.throws);413 },414 "custom stubbed method should not be proper stub": function () {415 var stub = sinon.stub(this.object, "method", function () {});416 refute.defined(stub.returns);417 refute.defined(stub.throws);418 },419 "stub should be spy": function () {420 var stub = sinon.stub(this.object, "method");421 this.object.method();422 assert(stub.called);423 assert(stub.calledOn(this.object));424 },425 "custom stubbed method should be spy": function () {426 var stub = sinon.stub(this.object, "method", function () {});427 this.object.method();428 assert(stub.called);429 assert(stub.calledOn(this.object));430 },431 "stub should affect spy": function () {432 var stub = sinon.stub(this.object, "method");433 stub.throws("TypeError");434 try {435 this.object.method();436 }437 catch (e) {} // eslint-disable-line no-empty438 assert(stub.threw("TypeError"));439 },440 "returns standalone stub without arguments": function () {441 var stub = sinon.stub();442 assert.isFunction(stub);443 assert.isFalse(stub.called);444 },445 "throws if property is not a function": function () {446 var obj = { someProp: 42 };447 assert.exception(function () {448 sinon.stub(obj, "someProp");449 });450 assert.equals(obj.someProp, 42);451 },452 "successfully stubs falsey properties": function () {453 var obj = { 0: function () { } };454 sinon.stub(obj, 0, function () {455 return "stubbed value";456 });457 assert.equals(obj[0](), "stubbed value");458 },459 "does not stub function object": function () {460 assert.exception(function () {461 sinon.stub(function () {});462 });463 }464 },465 everything: {466 "stubs all methods of object without property": function () {467 var obj = {468 func1: function () {},469 func2: function () {},470 func3: function () {}471 };472 sinon.stub(obj);473 assert.isFunction(obj.func1.restore);474 assert.isFunction(obj.func2.restore);475 assert.isFunction(obj.func3.restore);476 },477 "stubs prototype methods": function () {478 function Obj() {}479 Obj.prototype.func1 = function () {};480 var obj = new Obj();481 sinon.stub(obj);482 assert.isFunction(obj.func1.restore);483 },484 "returns object": function () {485 var object = {};486 assert.same(sinon.stub(object), object);487 },488 "only stubs functions": function () {489 var object = { foo: "bar" };490 sinon.stub(object);491 assert.equals(object.foo, "bar");492 }493 },494 "stubbed function": {495 "throws if stubbing non-existent property": function () {496 var myObj = {};497 assert.exception(function () {498 sinon.stub(myObj, "ouch");499 });500 refute.defined(myObj.ouch);501 },502 "has toString method": function () {503 var obj = { meth: function () {} };504 sinon.stub(obj, "meth");505 assert.equals(obj.meth.toString(), "meth");506 },507 "toString should say 'stub' when unable to infer name": function () {508 var stub = sinon.stub();509 assert.equals(stub.toString(), "stub");510 },511 "toString should prefer property name if possible": function () {512 var obj = {};513 obj.meth = sinon.stub();514 obj.meth();515 assert.equals(obj.meth.toString(), "meth");516 }517 },518 ".yields": {519 "invokes only argument as callback": function () {520 var stub = sinon.stub().yields();521 var spy = sinon.spy();522 stub(spy);523 assert(spy.calledOnce);524 assert.equals(spy.args[0].length, 0);525 },526 "throws understandable error if no callback is passed": function () {527 var stub = sinon.stub().yields();528 try {529 stub();530 throw new Error();531 } catch (e) {532 assert.equals(e.message, "stub expected to yield, but no callback was passed.");533 }534 },535 "includes stub name and actual arguments in error": function () {536 var myObj = { somethingAwesome: function () {} };537 var stub = sinon.stub(myObj, "somethingAwesome").yields();538 try {539 stub(23, 42);540 throw new Error();541 } catch (e) {542 assert.equals(e.message, "somethingAwesome expected to yield, but no callback " +543 "was passed. Received [23, 42]");544 }545 },546 "invokes last argument as callback": function () {547 var stub = sinon.stub().yields();548 var spy = sinon.spy();549 stub(24, {}, spy);550 assert(spy.calledOnce);551 assert.equals(spy.args[0].length, 0);552 },553 "invokes first of two callbacks": function () {554 var stub = sinon.stub().yields();555 var spy = sinon.spy();556 var spy2 = sinon.spy();557 stub(24, {}, spy, spy2);558 assert(spy.calledOnce);559 assert(!spy2.called);560 },561 "invokes callback with arguments": function () {562 var obj = { id: 42 };563 var stub = sinon.stub().yields(obj, "Crazy");564 var spy = sinon.spy();565 stub(spy);566 assert(spy.calledWith(obj, "Crazy"));567 },568 "throws if callback throws": function () {569 var obj = { id: 42 };570 var stub = sinon.stub().yields(obj, "Crazy");571 var callback = sinon.stub().throws();572 assert.exception(function () {573 stub(callback);574 });575 },576 "plays nice with throws": function () {577 var stub = sinon.stub().throws().yields();578 var spy = sinon.spy();579 assert.exception(function () {580 stub(spy);581 });582 assert(spy.calledOnce);583 },584 "plays nice with returns": function () {585 var obj = {};586 var stub = sinon.stub().returns(obj).yields();587 var spy = sinon.spy();588 assert.same(stub(spy), obj);589 assert(spy.calledOnce);590 },591 "plays nice with returnsArg": function () {592 var stub = sinon.stub().returnsArg(0).yields();593 var spy = sinon.spy();594 assert.same(stub(spy), spy);595 assert(spy.calledOnce);596 },597 "plays nice with returnsThis": function () {598 var obj = {};599 var stub = sinon.stub().returnsThis().yields();600 var spy = sinon.spy();601 assert.same(stub.call(obj, spy), obj);602 assert(spy.calledOnce);603 }604 },605 ".yieldsRight": {606 "invokes only argument as callback": function () {607 var stub = sinon.stub().yieldsRight();608 var spy = sinon.spy();609 stub(spy);610 assert(spy.calledOnce);611 assert.equals(spy.args[0].length, 0);612 },613 "throws understandable error if no callback is passed": function () {614 var stub = sinon.stub().yieldsRight();615 try {616 stub();617 throw new Error();618 } catch (e) {619 assert.equals(e.message, "stub expected to yield, but no callback was passed.");620 }621 },622 "includes stub name and actual arguments in error": function () {623 var myObj = { somethingAwesome: function () {} };624 var stub = sinon.stub(myObj, "somethingAwesome").yieldsRight();625 try {626 stub(23, 42);627 throw new Error();628 } catch (e) {629 assert.equals(e.message, "somethingAwesome expected to yield, but no callback " +630 "was passed. Received [23, 42]");631 }632 },633 "invokes last argument as callback": function () {634 var stub = sinon.stub().yieldsRight();635 var spy = sinon.spy();636 stub(24, {}, spy);637 assert(spy.calledOnce);638 assert.equals(spy.args[0].length, 0);639 },640 "invokes the last of two callbacks": function () {641 var stub = sinon.stub().yieldsRight();642 var spy = sinon.spy();643 var spy2 = sinon.spy();644 stub(24, {}, spy, spy2);645 assert(!spy.called);646 assert(spy2.calledOnce);647 },648 "invokes callback with arguments": function () {649 var obj = { id: 42 };650 var stub = sinon.stub().yieldsRight(obj, "Crazy");651 var spy = sinon.spy();652 stub(spy);653 assert(spy.calledWith(obj, "Crazy"));654 },655 "throws if callback throws": function () {656 var obj = { id: 42 };657 var stub = sinon.stub().yieldsRight(obj, "Crazy");658 var callback = sinon.stub().throws();659 assert.exception(function () {660 stub(callback);661 });662 },663 "plays nice with throws": function () {664 var stub = sinon.stub().throws().yieldsRight();665 var spy = sinon.spy();666 assert.exception(function () {667 stub(spy);668 });669 assert(spy.calledOnce);670 },671 "plays nice with returns": function () {672 var obj = {};673 var stub = sinon.stub().returns(obj).yieldsRight();674 var spy = sinon.spy();675 assert.same(stub(spy), obj);676 assert(spy.calledOnce);677 },678 "plays nice with returnsArg": function () {679 var stub = sinon.stub().returnsArg(0).yieldsRight();680 var spy = sinon.spy();681 assert.same(stub(spy), spy);682 assert(spy.calledOnce);683 },684 "plays nice with returnsThis": function () {685 var obj = {};686 var stub = sinon.stub().returnsThis().yieldsRight();687 var spy = sinon.spy();688 assert.same(stub.call(obj, spy), obj);689 assert(spy.calledOnce);690 }691 },692 ".yieldsOn": {693 setUp: function () {694 this.stub = sinon.stub.create();695 this.fakeContext = { foo: "bar" };696 },697 "invokes only argument as callback": function () {698 var spy = sinon.spy();699 this.stub.yieldsOn(this.fakeContext);700 this.stub(spy);701 assert(spy.calledOnce);702 assert(spy.calledOn(this.fakeContext));703 assert.equals(spy.args[0].length, 0);704 },705 "throws if no context is specified": function () {706 assert.exception(function () {707 this.stub.yieldsOn();708 }, "TypeError");709 },710 "throws understandable error if no callback is passed": function () {711 this.stub.yieldsOn(this.fakeContext);712 try {713 this.stub();714 throw new Error();715 } catch (e) {716 assert.equals(e.message, "stub expected to yield, but no callback was passed.");717 }718 },719 "includes stub name and actual arguments in error": function () {720 var myObj = { somethingAwesome: function () {} };721 var stub = sinon.stub(myObj, "somethingAwesome").yieldsOn(this.fakeContext);722 try {723 stub(23, 42);724 throw new Error();725 } catch (e) {726 assert.equals(e.message, "somethingAwesome expected to yield, but no callback " +727 "was passed. Received [23, 42]");728 }729 },730 "invokes last argument as callback": function () {731 var spy = sinon.spy();732 this.stub.yieldsOn(this.fakeContext);733 this.stub(24, {}, spy);734 assert(spy.calledOnce);735 assert(spy.calledOn(this.fakeContext));736 assert.equals(spy.args[0].length, 0);737 },738 "invokes first of two callbacks": function () {739 var spy = sinon.spy();740 var spy2 = sinon.spy();741 this.stub.yieldsOn(this.fakeContext);742 this.stub(24, {}, spy, spy2);743 assert(spy.calledOnce);744 assert(spy.calledOn(this.fakeContext));745 assert(!spy2.called);746 },747 "invokes callback with arguments": function () {748 var obj = { id: 42 };749 var spy = sinon.spy();750 this.stub.yieldsOn(this.fakeContext, obj, "Crazy");751 this.stub(spy);752 assert(spy.calledWith(obj, "Crazy"));753 assert(spy.calledOn(this.fakeContext));754 },755 "throws if callback throws": function () {756 var obj = { id: 42 };757 var callback = sinon.stub().throws();758 this.stub.yieldsOn(this.fakeContext, obj, "Crazy");759 assert.exception(function () {760 this.stub(callback);761 });762 }763 },764 ".yieldsTo": {765 "yields to property of object argument": function () {766 var stub = sinon.stub().yieldsTo("success");767 var callback = sinon.spy();768 stub({ success: callback });769 assert(callback.calledOnce);770 assert.equals(callback.args[0].length, 0);771 },772 "throws understandable error if no object with callback is passed": function () {773 var stub = sinon.stub().yieldsTo("success");774 try {775 stub();776 throw new Error();777 } catch (e) {778 assert.equals(e.message, "stub expected to yield to 'success', but no object " +779 "with such a property was passed.");780 }781 },782 "includes stub name and actual arguments in error": function () {783 var myObj = { somethingAwesome: function () {} };784 var stub = sinon.stub(myObj, "somethingAwesome").yieldsTo("success");785 try {786 stub(23, 42);787 throw new Error();788 } catch (e) {789 assert.equals(e.message, "somethingAwesome expected to yield to 'success', but " +790 "no object with such a property was passed. " +791 "Received [23, 42]");792 }793 },794 "invokes property on last argument as callback": function () {795 var stub = sinon.stub().yieldsTo("success");796 var callback = sinon.spy();797 stub(24, {}, { success: callback });798 assert(callback.calledOnce);799 assert.equals(callback.args[0].length, 0);800 },801 "invokes first of two possible callbacks": function () {802 var stub = sinon.stub().yieldsTo("error");803 var callback = sinon.spy();804 var callback2 = sinon.spy();805 stub(24, {}, { error: callback }, { error: callback2 });806 assert(callback.calledOnce);807 assert(!callback2.called);808 },809 "invokes callback with arguments": function () {810 var obj = { id: 42 };811 var stub = sinon.stub().yieldsTo("success", obj, "Crazy");812 var callback = sinon.spy();813 stub({ success: callback });814 assert(callback.calledWith(obj, "Crazy"));815 },816 "throws if callback throws": function () {817 var obj = { id: 42 };818 var stub = sinon.stub().yieldsTo("error", obj, "Crazy");819 var callback = sinon.stub().throws();820 assert.exception(function () {821 stub({ error: callback });822 });823 }824 },825 ".yieldsToOn": {826 setUp: function () {827 this.stub = sinon.stub.create();828 this.fakeContext = { foo: "bar" };829 },830 "yields to property of object argument": function () {831 this.stub.yieldsToOn("success", this.fakeContext);832 var callback = sinon.spy();833 this.stub({ success: callback });834 assert(callback.calledOnce);835 assert(callback.calledOn(this.fakeContext));836 assert.equals(callback.args[0].length, 0);837 },838 "throws if no context is specified": function () {839 assert.exception(function () {840 this.stub.yieldsToOn("success");841 }, "TypeError");842 },843 "throws understandable error if no object with callback is passed": function () {844 this.stub.yieldsToOn("success", this.fakeContext);845 try {846 this.stub();847 throw new Error();848 } catch (e) {849 assert.equals(e.message, "stub expected to yield to 'success', but no object " +850 "with such a property was passed.");851 }852 },853 "includes stub name and actual arguments in error": function () {854 var myObj = { somethingAwesome: function () {} };855 var stub = sinon.stub(myObj, "somethingAwesome").yieldsToOn("success", this.fakeContext);856 try {857 stub(23, 42);858 throw new Error();859 } catch (e) {860 assert.equals(e.message, "somethingAwesome expected to yield to 'success', but " +861 "no object with such a property was passed. " +862 "Received [23, 42]");863 }864 },865 "invokes property on last argument as callback": function () {866 var callback = sinon.spy();867 this.stub.yieldsToOn("success", this.fakeContext);868 this.stub(24, {}, { success: callback });869 assert(callback.calledOnce);870 assert(callback.calledOn(this.fakeContext));871 assert.equals(callback.args[0].length, 0);872 },873 "invokes first of two possible callbacks": function () {874 var callback = sinon.spy();875 var callback2 = sinon.spy();876 this.stub.yieldsToOn("error", this.fakeContext);877 this.stub(24, {}, { error: callback }, { error: callback2 });878 assert(callback.calledOnce);879 assert(callback.calledOn(this.fakeContext));880 assert(!callback2.called);881 },882 "invokes callback with arguments": function () {883 var obj = { id: 42 };884 var callback = sinon.spy();885 this.stub.yieldsToOn("success", this.fakeContext, obj, "Crazy");886 this.stub({ success: callback });887 assert(callback.calledOn(this.fakeContext));888 assert(callback.calledWith(obj, "Crazy"));889 },890 "throws if callback throws": function () {891 var obj = { id: 42 };892 var callback = sinon.stub().throws();893 this.stub.yieldsToOn("error", this.fakeContext, obj, "Crazy");894 assert.exception(function () {895 this.stub({ error: callback });896 });897 }898 },899 ".withArgs": {900 "defines withArgs method": function () {901 var stub = sinon.stub();902 assert.isFunction(stub.withArgs);903 },904 "creates filtered stub": function () {905 var stub = sinon.stub();906 var other = stub.withArgs(23);907 refute.same(other, stub);908 assert.isFunction(stub.returns);909 assert.isFunction(other.returns);910 },911 "filters return values based on arguments": function () {912 var stub = sinon.stub().returns(23);913 stub.withArgs(42).returns(99);914 assert.equals(stub(), 23);915 assert.equals(stub(42), 99);916 },917 "filters exceptions based on arguments": function () {918 var stub = sinon.stub().returns(23);919 stub.withArgs(42).throws();920 refute.exception(stub);921 assert.exception(function () {922 stub(42);923 });924 }925 },926 ".callsArgAsync": {927 setUp: function () {928 this.stub = sinon.stub.create();929 },930 "asynchronously calls argument at specified index": function (done) {931 this.stub.callsArgAsync(2);932 var callback = sinon.spy(done);933 this.stub(1, 2, callback);934 assert(!callback.called);935 }936 },937 ".callsArgWithAsync": {938 setUp: function () {939 this.stub = sinon.stub.create();940 },941 "asynchronously calls callback at specified index with multiple args": function (done) {942 var object = {};943 var array = [];944 this.stub.callsArgWithAsync(1, object, array);945 var callback = sinon.spy(done(function () {946 assert(callback.calledWith(object, array));947 }));948 this.stub(1, callback);949 assert(!callback.called);950 }951 },952 ".callsArgOnAsync": {953 setUp: function () {954 this.stub = sinon.stub.create();955 this.fakeContext = {956 foo: "bar"957 };958 },959 "asynchronously calls argument at specified index with specified context": function (done) {960 var context = this.fakeContext;961 this.stub.callsArgOnAsync(2, context);962 var callback = sinon.spy(done(function () {963 assert(callback.calledOn(context));964 }));965 this.stub(1, 2, callback);966 assert(!callback.called);967 }968 },969 ".callsArgOnWithAsync": {970 setUp: function () {971 this.stub = sinon.stub.create();972 this.fakeContext = { foo: "bar" };973 },974 "asynchronously calls argument at specified index with provided context and args": function (done) {975 var object = {};976 var context = this.fakeContext;977 this.stub.callsArgOnWithAsync(1, context, object);978 var callback = sinon.spy(done(function () {979 assert(callback.calledOn(context));980 assert(callback.calledWith(object));981 }));982 this.stub(1, callback);983 assert(!callback.called);984 }985 },986 ".yieldsAsync": {987 "asynchronously invokes only argument as callback": function (done) {988 var stub = sinon.stub().yieldsAsync();989 var spy = sinon.spy(done);990 stub(spy);991 assert(!spy.called);992 }993 },994 ".yieldsOnAsync": {995 setUp: function () {996 this.stub = sinon.stub.create();997 this.fakeContext = { foo: "bar" };998 },999 "asynchronously invokes only argument as callback with given context": function (done) {1000 var context = this.fakeContext;1001 this.stub.yieldsOnAsync(context);1002 var spy = sinon.spy(done(function () {1003 assert(spy.calledOnce);1004 assert(spy.calledOn(context));1005 assert.equals(spy.args[0].length, 0);1006 }));1007 this.stub(spy);1008 assert(!spy.called);1009 }1010 },1011 ".yieldsToAsync": {1012 "asynchronously yields to property of object argument": function (done) {1013 var stub = sinon.stub().yieldsToAsync("success");1014 var callback = sinon.spy(done(function () {1015 assert(callback.calledOnce);1016 assert.equals(callback.args[0].length, 0);1017 }));1018 stub({ success: callback });1019 assert(!callback.called);1020 }1021 },1022 ".yieldsToOnAsync": {1023 setUp: function () {1024 this.stub = sinon.stub.create();1025 this.fakeContext = { foo: "bar" };1026 },1027 "asynchronously yields to property of object argument with given context": function (done) {1028 var context = this.fakeContext;1029 this.stub.yieldsToOnAsync("success", context);1030 var callback = sinon.spy(done(function () {1031 assert(callback.calledOnce);1032 assert(callback.calledOn(context));1033 assert.equals(callback.args[0].length, 0);1034 }));1035 this.stub({ success: callback });1036 assert(!callback.called);1037 }1038 },1039 ".onCall": {1040 "can be used with returns to produce sequence": function () {1041 var stub = sinon.stub().returns(3);1042 stub.onFirstCall().returns(1)1043 .onCall(2).returns(2);1044 assert.same(stub(), 1);1045 assert.same(stub(), 3);1046 assert.same(stub(), 2);1047 assert.same(stub(), 3);1048 },1049 "can be used with returnsArg to produce sequence": function () {1050 var stub = sinon.stub().returns("default");1051 stub.onSecondCall().returnsArg(0);1052 assert.same(stub(1), "default");1053 assert.same(stub(2), 2);1054 assert.same(stub(3), "default");1055 },1056 "can be used with returnsThis to produce sequence": function () {1057 var instance = {};1058 instance.stub = sinon.stub().returns("default");1059 instance.stub.onSecondCall().returnsThis();1060 assert.same(instance.stub(), "default");1061 assert.same(instance.stub(), instance);1062 assert.same(instance.stub(), "default");1063 },1064 "can be used with throwsException to produce sequence": function () {1065 var stub = sinon.stub();1066 var error = new Error();1067 stub.onSecondCall().throwsException(error);1068 stub();1069 try {1070 stub();1071 fail("Expected stub to throw");1072 } catch (e) {1073 assert.same(e, error);1074 }1075 },1076 "in combination with withArgs": {1077 "can produce a sequence for a fake": function () {1078 var stub = sinon.stub().returns(0);1079 stub.withArgs(5).returns(-1)1080 .onFirstCall().returns(1)1081 .onSecondCall().returns(2);1082 assert.same(stub(0), 0);1083 assert.same(stub(5), 1);1084 assert.same(stub(0), 0);1085 assert.same(stub(5), 2);1086 assert.same(stub(5), -1);1087 },1088 "falls back to stub default behaviour if fake does not have its own default behaviour": function () {1089 var stub = sinon.stub().returns(0);1090 stub.withArgs(5)1091 .onFirstCall().returns(1);1092 assert.same(stub(5), 1);1093 assert.same(stub(5), 0);1094 },1095 "falls back to stub behaviour for call if fake does not have its own behaviour for call": function () {1096 var stub = sinon.stub().returns(0);1097 stub.withArgs(5).onFirstCall().returns(1);1098 stub.onSecondCall().returns(2);1099 assert.same(stub(5), 1);1100 assert.same(stub(5), 2);1101 assert.same(stub(4), 0);1102 },1103 "defaults to undefined behaviour once no more calls have been defined": function () {1104 var stub = sinon.stub();1105 stub.withArgs(5).onFirstCall().returns(1)1106 .onSecondCall().returns(2);1107 assert.same(stub(5), 1);1108 assert.same(stub(5), 2);1109 refute.defined(stub(5));1110 },1111 "does not create undefined behaviour just by calling onCall": function () {1112 var stub = sinon.stub().returns(2);1113 stub.onFirstCall();1114 assert.same(stub(6), 2);1115 },1116 "works with fakes and reset": function () {1117 var stub = sinon.stub();1118 stub.withArgs(5).onFirstCall().returns(1);1119 stub.withArgs(5).onSecondCall().returns(2);1120 assert.same(stub(5), 1);1121 assert.same(stub(5), 2);1122 refute.defined(stub(5));1123 stub.reset();1124 assert.same(stub(5), 1);1125 assert.same(stub(5), 2);1126 refute.defined(stub(5));1127 },1128 "throws an understandable error when trying to use withArgs on behavior": function () {1129 try {1130 sinon.stub().onFirstCall().withArgs(1);1131 } catch (e) {1132 assert.match(e.message, /not supported/);1133 }1134 }1135 },1136 "can be used with yields* to produce a sequence": function () {1137 var context = { foo: "bar" };1138 var obj = { method1: sinon.spy(), method2: sinon.spy() };1139 var obj2 = { method2: sinon.spy() };1140 var stub = sinon.stub().yieldsToOn("method2", context, 7, 8);1141 stub.onFirstCall().yields(1, 2)1142 .onSecondCall().yieldsOn(context, 3, 4)1143 .onThirdCall().yieldsTo("method1", 5, 6)1144 .onCall(3).yieldsToOn("method2", context, 7, 8);1145 var spy1 = sinon.spy();1146 var spy2 = sinon.spy();1147 stub(spy1);1148 stub(spy2);1149 stub(obj);1150 stub(obj);1151 stub(obj2); // should continue with default behavior1152 assert(spy1.calledOnce);1153 assert(spy1.calledWithExactly(1, 2));1154 assert(spy2.calledOnce);1155 assert(spy2.calledAfter(spy1));1156 assert(spy2.calledOn(context));1157 assert(spy2.calledWithExactly(3, 4));1158 assert(obj.method1.calledOnce);1159 assert(obj.method1.calledAfter(spy2));1160 assert(obj.method1.calledWithExactly(5, 6));1161 assert(obj.method2.calledOnce);1162 assert(obj.method2.calledAfter(obj.method1));1163 assert(obj.method2.calledOn(context));1164 assert(obj.method2.calledWithExactly(7, 8));1165 assert(obj2.method2.calledOnce);1166 assert(obj2.method2.calledAfter(obj.method2));1167 assert(obj2.method2.calledOn(context));1168 assert(obj2.method2.calledWithExactly(7, 8));1169 },1170 "can be used with callsArg* to produce a sequence": function () {1171 var spy1 = sinon.spy();1172 var spy2 = sinon.spy();1173 var spy3 = sinon.spy();1174 var spy4 = sinon.spy();1175 var spy5 = sinon.spy();1176 var decoy = sinon.spy();1177 var context = { foo: "bar" };1178 var stub = sinon.stub().callsArgOnWith(3, context, "c", "d");1179 stub.onFirstCall().callsArg(0)1180 .onSecondCall().callsArgWith(1, "a", "b")1181 .onThirdCall().callsArgOn(2, context)1182 .onCall(3).callsArgOnWith(3, context, "c", "d");1183 stub(spy1);1184 stub(decoy, spy2);1185 stub(decoy, decoy, spy3);1186 stub(decoy, decoy, decoy, spy4);1187 stub(decoy, decoy, decoy, spy5); // should continue with default behavior1188 assert(spy1.calledOnce);1189 assert(spy2.calledOnce);1190 assert(spy2.calledAfter(spy1));1191 assert(spy2.calledWithExactly("a", "b"));1192 assert(spy3.calledOnce);1193 assert(spy3.calledAfter(spy2));1194 assert(spy3.calledOn(context));1195 assert(spy4.calledOnce);1196 assert(spy4.calledAfter(spy3));1197 assert(spy4.calledOn(context));1198 assert(spy4.calledWithExactly("c", "d"));1199 assert(spy5.calledOnce);1200 assert(spy5.calledAfter(spy4));1201 assert(spy5.calledOn(context));1202 assert(spy5.calledWithExactly("c", "d"));1203 assert(decoy.notCalled);1204 },1205 "can be used with yields* and callsArg* in combination to produce a sequence": function () {1206 var stub = sinon.stub().yields(1, 2);1207 stub.onSecondCall().callsArg(1)1208 .onThirdCall().yieldsTo("method")1209 .onCall(3).callsArgWith(2, "a", "b");1210 var obj = { method: sinon.spy() };1211 var spy1 = sinon.spy();1212 var spy2 = sinon.spy();1213 var spy3 = sinon.spy();1214 var decoy = sinon.spy();1215 stub(spy1);1216 stub(decoy, spy2);1217 stub(obj);1218 stub(decoy, decoy, spy3);1219 assert(spy1.calledOnce);1220 assert(spy2.calledOnce);1221 assert(spy2.calledAfter(spy1));1222 assert(obj.method.calledOnce);1223 assert(obj.method.calledAfter(spy2));1224 assert(spy3.calledOnce);1225 assert(spy3.calledAfter(obj.method));1226 assert(spy3.calledWithExactly("a", "b"));1227 assert(decoy.notCalled);1228 },1229 "should interact correctly with assertions (GH-231)": function () {1230 var stub = sinon.stub();1231 var spy = sinon.spy();1232 stub.callsArgWith(0, "a");1233 stub(spy);1234 assert(spy.calledWith("a"));1235 stub(spy);1236 assert(spy.calledWith("a"));1237 stub.onThirdCall().callsArgWith(0, "b");1238 stub(spy);1239 assert(spy.calledWith("b"));1240 }1241 },1242 "reset only resets call history": function () {1243 var obj = { a: function () {} };1244 var spy = sinon.spy();1245 sinon.stub(obj, "a").callsArg(1);1246 obj.a(null, spy);1247 obj.a.reset();1248 obj.a(null, spy);1249 assert(spy.calledTwice);1250 },1251 ".resetBehavior": {1252 "clears yields* and callsArg* sequence": function () {1253 var stub = sinon.stub().yields(1);1254 stub.onFirstCall().callsArg(1);1255 stub.resetBehavior();1256 stub.yields(3);1257 var spyWanted = sinon.spy();1258 var spyNotWanted = sinon.spy();1259 stub(spyWanted, spyNotWanted);1260 assert(spyNotWanted.notCalled);1261 assert(spyWanted.calledOnce);1262 assert(spyWanted.calledWithExactly(3));1263 },1264 "cleans 'returns' behavior": function () {1265 var stub = sinon.stub().returns(1);1266 stub.resetBehavior();1267 refute.defined(stub());1268 },1269 "cleans behavior of fakes returned by withArgs": function () {1270 var stub = sinon.stub();1271 stub.withArgs("lolz").returns(2);1272 stub.resetBehavior();1273 refute.defined(stub("lolz"));1274 },1275 "does not clean parents' behavior when called on a fake returned by withArgs": function () {1276 var parentStub = sinon.stub().returns(false);1277 var childStub = parentStub.withArgs("lolz").returns(true);1278 childStub.resetBehavior();1279 assert.same(parentStub("lolz"), false);1280 assert.same(parentStub(), false);1281 },1282 "cleans 'returnsArg' behavior": function () {1283 var stub = sinon.stub().returnsArg(0);1284 stub.resetBehavior();1285 refute.defined(stub("defined"));1286 },1287 "cleans 'returnsThis' behavior": function () {1288 var instance = {};1289 instance.stub = sinon.stub.create();1290 instance.stub.returnsThis();1291 instance.stub.resetBehavior();1292 refute.defined(instance.stub());1293 },1294 "does not touch properties that are reset by 'reset'": {1295 ".calledOnce": function () {1296 var stub = sinon.stub();1297 stub(1);1298 stub.resetBehavior();1299 assert(stub.calledOnce);1300 },1301 "called multiple times": function () {1302 var stub = sinon.stub();1303 stub(1);1304 stub(2);1305 stub(3);1306 stub.resetBehavior();1307 assert(stub.called);1308 assert.equals(stub.args.length, 3);1309 assert.equals(stub.returnValues.length, 3);1310 assert.equals(stub.exceptions.length, 3);1311 assert.equals(stub.thisValues.length, 3);1312 assert.defined(stub.firstCall);1313 assert.defined(stub.secondCall);1314 assert.defined(stub.thirdCall);1315 assert.defined(stub.lastCall);1316 },1317 "call order state": function () {1318 var stubs = [sinon.stub(), sinon.stub()];1319 stubs[0]();1320 stubs[1]();1321 stubs[0].resetBehavior();1322 assert(stubs[0].calledBefore(stubs[1]));1323 },1324 "fakes returned by withArgs": function () {1325 var stub = sinon.stub();1326 var fakeA = stub.withArgs("a");1327 var fakeB = stub.withArgs("b");1328 stub("a");1329 stub("b");1330 stub("c");1331 var fakeC = stub.withArgs("c");1332 stub.resetBehavior();1333 assert(fakeA.calledOnce);1334 assert(fakeB.calledOnce);1335 assert(fakeC.calledOnce);1336 }1337 }1338 },1339 ".length": {1340 "is zero by default": function () {1341 var stub = sinon.stub();1342 assert.equals(stub.length, 0);1343 },1344 "matches the function length": function () {1345 var api = { someMethod: function (a, b, c) {} }; // eslint-disable-line no-unused-vars1346 var stub = sinon.stub(api, "someMethod");1347 assert.equals(stub.length, 3);1348 }1349 }1350 });...

Full Screen

Full Screen

user-auth.controller.unit.js

Source:user-auth.controller.unit.js Github

copy

Full Screen

...102 req = {103 };104 res = {105 };106 statusStub = sinon.stub();107 sendStub = sinon.stub();108 109 statusStub.returnsThis();110 res.status = statusStub;111 res.send = sendStub;112 next = () => {113 };114 mockSharedModule = new MockSharedModule(mockLogger);115 userController = new UserController(mockLogger, mockSharedModule);116 //mongoose stubs117 saveStub = sinon.stub(Users.prototype, 'save');118 119 generateUniqueTokenStub = sinon.stub(mockSharedModule.authHelpers, 'generateUniqueToken');120 generateUniqueTokenStub.returns(token);121 122 generateUrlStub = sinon.stub(mockSharedModule.authHelpers, 'generateUrl');123 generateUrlStub.returns('http://blahblah.com');124 });125 afterEach(() => {126 // statusStub and sendStub are anonymous stubs so the do not have to be127 // restored128 saveStub.restore();129 generateUniqueTokenStub.restore();130 });131 describe('#register', () => {132 var validReqBody = {133 username: 'testuser',134 email: 'test@example.com',135 password: '1234abcABC-'136 };137 beforeEach(() => {138 hashPasswordStub = sinon.stub(mockSharedModule.authHelpers, 'hashPassword');139 sendMailStub = sinon.stub(mockSharedModule.mail, 'sendMail');140 hashPasswordStub.resolves('hash');141 142 req.body = JSON.parse(JSON.stringify(validReqBody));143 });144 afterEach(() => {145 hashPasswordStub.restore();146 sendMailStub.restore();147 });148 function setupSaveResolves() {149 saveStub.resolves(mockUser);150 }151 function setupSendMailResolves() {152 sendMailStub.resolves(sendMailInfo);153 }154 function setupAllResolve() {155 setupSaveResolves();156 setupSendMailResolves();157 }158 it('should return a promise', () => {159 req.body = {160 username: 'newuser',161 email: 'test@example.com',162 password: '1234abcABC-'163 };164 userController.register(req, res, next)165 .constructor.name.should.equal('Promise');166 });167 it('should use authHelpers.hashPassword to hash the password', () => {168 setupAllResolve();169 return userController.register(req, res, next).then((data) => {170 hashPasswordStub.args.should.deep.equal([[ req.body.password ]]);171 });172 });173 it('should use authHelpers.generateUniqueToken', () => {174 setupAllResolve();175 return userController.register(req, res, next).then((data) => {176 generateUniqueTokenStub.args.should.deep.equal([[ ]]);177 });178 });179 it('should try to save the user', () => {180 setupAllResolve();181 return userController.register(req, res, next).then((data) => {182 saveStub.called.should.equal(true);183 });184 });185 it('should send back the saved user', () => {186 setupAllResolve();187 return userController.register(req, res, next).then((data) => {188 statusStub.args.should.deep.equal([[ 201 ]]);189 sendStub.args.should.deep.equal([[ { user: mockUser } ]]);190 });191 });192 it('should handle 11000 duplicate index', () => {193 saveStub.rejects({194 name: 'MongoError',195 toJSON: () => {196 return {197 code: 11000,198 errmsg: 'Duplicate index: username_1'199 };200 },201 code: 11000,202 });203 return userController.register(req, res, next).then((data) => {204 statusStub.args.should.deep.equal([[ 400 ]]);205 sendStub.calledWith({ error: 'Username is taken' });206 });207 });208 it('should send a 500 if the duplicate key is not username', () => {209 saveStub.rejects({210 name: 'MongoError',211 toJSON: () => {212 return {213 code: 11000,214 errmsg: 'Duplicate index: email_1'215 };216 },217 code: 11000,218 });219 return userController.register(req, res, next).then((data) => {220 statusStub.args.should.deep.equal([[ 500 ]]);221 // response should be generic222 sendStub.calledWith('Internal Server Error');223 });224 });225 it('should handle invalid password as an error', () => {226 req.body.password = 'bad';227 return userController.register(req, res, next).then((data) => {228 statusStub.args.should.deep.equal([[ 400 ]]);229 });230 });231 it('should send a 500 if save fails', () => {232 saveStub.rejects(new Error('saveFailed'));233 return userController.register(req, res, next).then((data) => {234 statusStub.args.should.deep.equal([[ 500 ]]);235 sendStub.args.should.deep.equal([[ ]]);236 });237 });238 it('should use shared.sendMail to send the verification email', () => {239 setupAllResolve();240 return userController.register(req, res, next).then((data) => {241 sendMailStub.args.should.deep.equal([[ verifyMailParams ]]);242 });243 });244 it('should send a 201 with additional message if the email sending fails', () => {245 setupSaveResolves();246 sendMailStub.rejects(sendMailError);247 return userController.register(req, res, next).then((data) => {248 statusStub.args.should.deep.equal([[ 201 ]]);249 sendStub.args.should.deep.equal([[ { user: mockUser, message: 'Verification email not sent' }]]);250 });251 });252 253 it('should not allow registration if registration is disabled', async () => {254 setupAllResolve();255 mockConfig.app.allowRegistration = false;256 await userController.register(req, res, next);257 statusStub.args.should.deep.equal([[ 500 ]]);258 sendStub.called.should.equal(true);259 mockConfig.app.allowRegistration = true;260 });261 it('should not try to send an email if email sending is disabled', async () => {262 setupAllResolve();263 mockConfig.app.requireEmailVerification = false;264 await userController.register(req, res, next);265 statusStub.args.should.deep.equal([[ 201 ]]);266 sendStub.args.should.deep.equal([[ { user: mockUser } ]]);267 sendMailStub.args.should.deep.equal([]);268 mockConfig.app.requireEmailVerification = true;269 });270 });271 describe('#changePassword', () => {272 const oldPassword = '123';273 const newPassword = 'abcABC123-';274 const invalidPassword = '123';275 const validReqBody = {276 oldPassword: oldPassword,277 newPassword: newPassword278 };279 const match = true;280 const hash = 'hash';281 let hashPasswordStub, verifyPasswordStub;282 beforeEach(() => {283 req.body = validReqBody;284 req.body.newPassword = newPassword;285 req.user = mockUser;286 req.user.save = saveStub;287 hashPasswordStub = sinon.stub(mockSharedModule.authHelpers, 'hashPassword');288 verifyPasswordStub = sinon.stub(mockSharedModule.authHelpers, 'verifyPassword');289 });290 afterEach(() => {291 hashPasswordStub.restore();292 verifyPasswordStub.restore();293 });294 function setupAllResolve() {295 setupVerifyResolves();296 setupHashResolves();297 setupSaveResolves();298 }299 function setupVerifyResolves() {300 verifyPasswordStub.resolves(match);301 }302 function setupHashResolves() {303 hashPasswordStub.resolves(hash);304 }305 function setupSaveResolves() {306 saveStub.resolves(mockUser);307 }308 it('should return a promise', () => {309 setupAllResolve();310 userController.changePassword(req, res, next).constructor.name.should.equal('Promise');311 });312 it('should use authHelpers.verifyPassword', () => {313 setupAllResolve();314 return userController.changePassword(req, res, next).then((data) => {315 verifyPasswordStub.args.should.deep.equal([[ mockUser.password, oldPassword ]]);316 });317 });318 it('should use authHelpers.hashPassword', () => {319 setupAllResolve();320 return userController.changePassword(req, res, next).then((data) => {321 hashPasswordStub.args.should.deep.equal([[ newPassword ]]);322 });323 });324 it('should use user.save', () => {325 setupAllResolve();326 327 return userController.changePassword(req, res, next).then((data) => {328 saveStub.called.should.equal(true);329 });330 });331 it('should 200 with updated user on success', () => {332 setupAllResolve();333 return userController.changePassword(req, res, next).then((data) => {334 statusStub.args.should.deep.equal([[ 200 ]]);335 sendStub.args.should.deep.equal([[ mockUser ]]);336 });337 });338 it('should 400 on weak password', () => {339 setupVerifyResolves();340 req.body.newPassword = invalidPassword;341 return userController.changePassword(req, res, next).then((data) => {342 statusStub.args.should.deep.equal([[ 400 ]]);343 let args = sendStub.args;344 args.length.should.equal(1);345 args[0].length.should.equal(1);346 args[0][0].message.should.contain('Invalid password');347 });348 });349 it('should 400 on wrong old password', () => {350 verifyPasswordStub.resolves(false);351 return userController.changePassword(req, res, next).then((data) => {352 statusStub.args.should.deep.equal([[ 400 ]]);353 sendStub.args.should.deep.equal([[ { message: 'Incorrect Username/Password' } ]]);354 });355 });356 it('should 400 if save validator errors', () => {357 const validatorError = {358 name: 'ValidationError',359 message: 'Something is invalid',360 errors: [ { name: 'ValidatorError' } ]361 };362 setupVerifyResolves();363 setupHashResolves();364 saveStub.rejects(validatorError);365 return userController.changePassword(req, res, next).then((data) => {366 statusStub.args.should.deep.equal([[ 400 ]]);367 sendStub.args.should.deep.equal([[ { message: validatorError.message } ]]);368 });369 });370 it('should 500 if save fails', () => {371 const saveError = new Error('save error');372 setupVerifyResolves();373 setupHashResolves();374 saveStub.rejects(saveError);375 return userController.changePassword(req, res, next).then((data) => {376 statusStub.args.should.deep.equal([[ 500 ]]);377 sendStub.args.should.deep.equal([[ ]]);378 });379 });380 it('should 500 if verify fails', () => {381 const matchError = new Error('match error');382 verifyPasswordStub.rejects(matchError);383 return userController.changePassword(req, res, next).then((data) => {384 statusStub.args.should.deep.equal([[ 500 ]]);385 sendStub.args.should.deep.equal([[ ]]);386 });387 });388 it('should 500 if hash fails', () => {389 const hashError = new Error('hash error');390 setupVerifyResolves();391 hashPasswordStub.rejects(hashError);392 return userController.changePassword(req, res, next).then((data) => {393 statusStub.args.should.deep.equal([[ 500 ]]);394 sendStub.args.should.deep.equal([[ ]]);395 });396 });397 });398 describe('#verifyEmail', () => {399 let findOneStub;400 let execStub;401 beforeEach(() => {402 req.query = {403 token: token404 };405 mockUser.save = saveStub;406 findOneStub = sinon.stub(Users, 'findOne');407 execStub = sinon.stub();408 });409 afterEach(() => {410 findOneStub.restore();411 });412 function setupSaveResolves() {413 saveStub.resolves(mockUser);414 }415 function setupFindOneResolves() {416 execStub.resolves(mockUser);417 findOneStub.returns({418 exec: execStub419 });420 }421 function setupAllResolve() {422 setupSaveResolves();423 setupFindOneResolves();424 }425 it('should return a promise', () => {426 setupAllResolve();427 userController.verifyEmail(req, res, next).constructor.name428 .should.equal('Promise');429 });430 it('should use the users findOne method and exec it', () => {431 setupAllResolve();432 return userController.verifyEmail(req, res, next).then(() => {433 findOneStub.args.should.deep.equal([[ { 'verification.token': req.query.token } ]]);434 execStub.called.should.equal(true);435 });436 });437 it('should use user.save', () => {438 setupAllResolve();439 return userController.verifyEmail(req, res, next).then((data) => {440 saveStub.called.should.equal(true);441 });442 });443 it('should set the user as verified and remove the ttl', () => {444 setupAllResolve();445 mockUser.verified.should.equal(false);446 447 return userController.verifyEmail(req, res, next).then((data) => {448 mockUser.verified.should.equal(true);449 should.not.exist(mockUser.verification.expires);450 });451 });452 it('should send a 204 on success', () => {453 setupAllResolve();454 return userController.verifyEmail(req, res, next).then((data) => {455 statusStub.args.should.deep.equal([[ 204 ]]);456 sendStub.args.should.deep.equal([[ ]]);457 });458 });459 it('should send a 400 if the token does not exist', () => {460 setupFindOneResolves();461 execStub.resolves(null);462 req.query.token = 'xyz';463 return userController.verifyEmail(req, res, next).then(() => {464 statusStub.args.should.deep.equal([[ 400 ]]);465 sendStub.args.should.deep.equal([[ { message: 'Token invalid' } ]]);466 });467 });468 it('should send a 500 if the save fails', () => {469 setupFindOneResolves();470 saveStub.rejects(new Error('save failed'));471 return userController.verifyEmail(req, res, next).then((data) => {472 statusStub.args.should.deep.equal([[ 500 ]]);473 sendStub.args.should.deep.equal([[ ]]);474 });475 });476 it('should send a 400 if the ttl has passed', () => {477 // set expire time to some time in the past478 setupFindOneResolves();479 mockUser.verification.expires = Date.now() - 100000;480 return userController.verifyEmail(req, res, next).then((data) => {481 saveStub.called.should.equal(false);482 statusStub.args.should.deep.equal([[ 400 ]]);483 sendStub.args.should.deep.equal([[ { message: 'Token has expired' } ]]);484 });485 });486 });487 describe('#requestVerificationEmail', () => {488 beforeEach(() => {489 sendMailStub = sinon.stub(mockSharedModule.mail, 'sendMail');490 req.user = mockUser;491 req.user.save = saveStub;492 });493 afterEach(() => {494 });495 function setupSaveResolves() {496 saveStub.resolves(mockUser);497 }498 function setupSendMailResolves() {499 sendMailStub.resolves(sendMailInfo);500 }501 function setupAllResolve() {502 setupSaveResolves();503 setupSendMailResolves();504 }505 it('should return a promise', () => {506 setupAllResolve();507 userController.requestVerificationEmail(req, res, next)508 .constructor.name.should.equal('Promise');509 });510 it('should use user.save', () => {511 setupAllResolve();512 return userController.requestVerificationEmail(req, res, next).then((data) => {513 saveStub.called.should.equal(true);514 });515 });516 it('should set up a new token and ttl', () => {517 let oldTTL, newTTL, oldToken, newToken;518 oldToken = 'old';519 oldTTL = Date.now() - 10000;520 mockUser.verification.token = oldToken;521 mockUser.verification.expires = oldTTL;522 setupAllResolve();523 return userController.requestVerificationEmail(req, res, next).then((data) => {524 newToken = mockUser.verification.token;525 newTTL = mockUser.verification.expires;526 should.exist(newToken);527 newToken.should.not.equal(oldToken);528 should.exist(oldToken);529 newTTL.should.be.above(oldTTL);530 });531 });532 it('should send a 204 on success', () => {533 setupAllResolve();534 return userController.requestVerificationEmail(req, res, next).then((data) => {535 statusStub.args.should.deep.equal([[ 204 ]]);536 sendStub.args.should.deep.equal([[ ]]);537 });538 });539 it('should send a 500 if the save fails', () => {540 saveStub.rejects(new Error('Save failed'));541 return userController.requestVerificationEmail(req, res, next).then((data) => {542 statusStub.args.should.deep.equal([[ 500 ]]);543 sendStub.args.should.deep.equal([[ ]]);544 });545 });546 it('should use authHelpers.generateUrl', () => {547 setupAllResolve();548 return userController.requestVerificationEmail(req, res, next).then((data) => {549 generateUrlStub.args.should.deep.equal([[ ]]);550 });551 });552 553 it('should use authHelpers.generateUniqueToken', () => {554 setupAllResolve();555 return userController.requestVerificationEmail(req, res, next).then((data) => {556 generateUniqueTokenStub.args.should.deep.equal([[ ]]);557 });558 });559 560 it('should use shared.sendMail to send the verification email', () => {561 setupAllResolve();562 return userController.requestVerificationEmail(req, res, next).then((data) => {563 sendMailStub.args.should.deep.equal([[ verifyMailParams ]]);564 });565 });566 it('should send a 500 if sendmail fails', () => {567 setupSaveResolves();568 sendMailStub.rejects(sendMailError);569 return userController.requestVerificationEmail(req, res, next).then((data) => {570 statusStub.args.should.deep.equal([[ 500 ]]);571 sendStub.args.should.deep.equal([[ ]]);572 });573 });574 });575 576 describe('#requestChangePasswordEmail', () => {577 let findMock;578 beforeEach(() => {579 sendMailStub = sinon.stub(mockSharedModule.mail, 'sendMail');580 usersMock = sinon.mock(Users);581 req.query = {582 email: mockUser.email583 };584 mockUser.verified = true;585 req.user = mockUser;586 req.user.save = saveStub;587 });588 afterEach(() => {589 usersMock.restore();590 });591 function setupSaveResolves() {592 saveStub.resolves(mockUser);593 }594 function setupSendMailResolves() {595 sendMailStub.resolves(sendMailInfo);596 }597 function setupFindResolves() {598 usersMock.expects('find')599 .chain('exec')600 .resolves([ mockUser ]);601 }602 function setupAllResolve() {603 setupSaveResolves();604 setupSendMailResolves();605 setupFindResolves();606 }607 it('should return a promise', () => {608 setupAllResolve();609 userController.requestChangePasswordEmail(req, res, next)610 .constructor.name.should.equal('Promise');611 });612 it('should use user.save', () => {613 setupAllResolve();614 return userController.requestChangePasswordEmail(req, res, next).then((data) => {615 saveStub.called.should.equal(true);616 });617 });618 it('should set up a new token and ttl', () => {619 let oldTTL, newTTL, oldToken, newToken;620 oldToken = 'old';621 oldTTL = Date.now() - 10000;622 mockUser.resetPassword = {623 token: oldToken,624 expires: oldTTL625 };626 setupAllResolve();627 return userController.requestChangePasswordEmail(req, res, next).then((data) => {628 newToken = mockUser.resetPassword.token;629 newTTL = mockUser.resetPassword.expires;630 should.exist(newToken);631 newToken.should.not.equal(oldToken);632 should.exist(oldToken);633 newTTL.should.be.above(oldTTL);634 });635 });636 it('should send a 204 on success', () => {637 setupAllResolve();638 return userController.requestChangePasswordEmail(req, res, next).then((data) => {639 statusStub.args.should.deep.equal([[ 204 ]]);640 sendStub.args.should.deep.equal([[ ]]);641 });642 });643 it('should send a 500 if the save fails', () => {644 setupFindResolves();645 saveStub.rejects(new Error('Save failed'));646 return userController.requestChangePasswordEmail(req, res, next).then((data) => {647 statusStub.args.should.deep.equal([[ 500 ]]);648 sendStub.args.should.deep.equal([[ ]]);649 });650 });651 652 it('should use authHelpers.generateUrl', () => {653 setupAllResolve();654 return userController.requestVerificationEmail(req, res, next).then((data) => {655 generateUrlStub.args.should.deep.equal([[ ]]);656 });657 });658 659 it('should use authHelpers.generateUniqueToken', () => {660 setupAllResolve();661 return userController.requestChangePasswordEmail(req, res, next).then((data) => {662 generateUniqueTokenStub.args.should.deep.equal([[ ]]);663 });664 });665 666 it('should use shared.sendMail to send the password reset email', () => {667 setupAllResolve();668 return userController.requestChangePasswordEmail(req, res, next).then((data) => {669 sendMailStub.args.should.deep.equal([[ passwordMailParams ]]);670 });671 });672 it('should send a 500 if sendmail fails', () => {673 setupSaveResolves();674 setupFindResolves();675 sendMailStub.rejects(sendMailError);676 return userController.requestChangePasswordEmail(req, res, next).then((data) => {677 statusStub.args.should.deep.equal([[ 500 ]]);678 sendStub.args.should.deep.equal([[ ]]);679 });680 });681 it('should send a 400 if email is missing', () => {682 req.query = {};683 return userController.requestChangePasswordEmail(req, res, next).then((data) => {684 statusStub.args.should.deep.equal([[ 400 ]]);685 sendStub.args.should.deep.equal([[ { error: 'Missing email' } ]]);686 });687 });688 it('should use Users.find', () => {689 setupSaveResolves();690 setupSendMailResolves();691 usersMock.expects('find')692 .withExactArgs({ email: req.query.email })693 .chain('exec')694 .resolves([ mockUser ]);695 return userController.requestChangePasswordEmail(req, res, next).then((data) => {696 usersMock.verify();697 });698 });699 it('should send 204 if the user is not found', () => {700 // we dont want someone to be able to enumerate emails701 usersMock.expects('find')702 .chain('exec')703 .resolves([]);704 return userController.requestChangePasswordEmail(req, res, next).then((data) => {705 statusStub.args.should.deep.equal([[ 400 ]]);706 sendStub.args.should.deep.equal([[ { error: 'Email not found' } ]]);707 });708 });709 it('should send a 500 if the find fails', () => {710 usersMock.expects('find')711 .chain('exec')712 .rejects(new Error('Not found'));713 return userController.requestChangePasswordEmail(req, res, next).then((data) => {714 statusStub.args.should.deep.equal([[ 500 ]]);715 sendStub.args.should.deep.equal([[ ]]);716 });717 });718 });719 720 describe('#resetPassword', () => {721 const newPassword = 'abcABC123-';722 const weakPassword = 'abc';723 const hash = 'hash';724 beforeEach(() => {725 req.user = mockUser;726 req.body = {727 password: newPassword,728 token: token729 };730 731 mockUser.save = saveStub;732 mockUser.resetPassword = {733 token: token,734 expires: Date.now() + 500735 };736 hashPasswordStub = sinon.stub(mockSharedModule.authHelpers, 'hashPassword');737 usersMock = sinon.mock(Users);738 });739 afterEach(() => {740 hashPasswordStub.restore();741 usersMock.restore();742 });743 function setupSaveResolves() {744 saveStub.resolves(mockUser);745 }746 function setupFindResolves() {747 usersMock.expects('find')748 .chain('exec')749 .resolves([ mockUser ]);750 }...

Full Screen

Full Screen

getWebGLStub.js

Source:getWebGLStub.js Github

copy

Full Screen

1define([2 'Core/clone',3 'Core/defaultValue',4 'Core/defined',5 'Core/DeveloperError',6 'Core/WebGLConstants'7 ], function(8 clone,9 defaultValue,10 defined,11 DeveloperError,12 WebGLConstants) {13 'use strict';14 function getWebGLStub(canvas, options) {15 var stub = clone(WebGLConstants);16 stub.canvas = canvas;17 stub.drawingBufferWidth = Math.max(canvas.width, 1);18 stub.drawingBufferHeight = Math.max(canvas.height, 1);19 stub.activeTexture = noop;20 stub.attachShader = noop;21 stub.bindAttribLocation = noop;22 stub.bindBuffer = noop;23 stub.bindFramebuffer = noop;24 stub.bindRenderbuffer = noop;25 stub.bindTexture = noop;26 stub.blendColor = noop;27 stub.blendEquation = noop;28 stub.blendEquationSeparate = noop;29 stub.blendFunc = noop;30 stub.blendFuncSeparate = noop;31 stub.bufferData = noop;32 stub.bufferSubData = noop;33 stub.checkFramebufferStatus = checkFramebufferStatusStub;34 stub.clear = noop;35 stub.clearColor = noop;36 stub.clearDepth = noop;37 stub.clearStencil = noop;38 stub.colorMask = noop;39 stub.compileShader = noop;40 stub.compressedTexImage2D = noop;41 stub.compressedTexSubImage2D = noop;42 stub.copyTexImage2D = noop;43 stub.copyTexSubImage2D = noop;44 stub.createBuffer = createStub;45 stub.createFramebuffer = createStub;46 stub.createProgram = createStub;47 stub.createRenderbuffer = createStub;48 stub.createShader = createStub;49 stub.createTexture = createStub;50 stub.cullFace = noop;51 stub.deleteBuffer = noop;52 stub.deleteFramebuffer = noop;53 stub.deleteProgram = noop;54 stub.deleteRenderbuffer = noop;55 stub.deleteShader = noop;56 stub.deleteTexture = noop;57 stub.depthFunc = noop;58 stub.depthMask = noop;59 stub.depthRange = noop;60 stub.detachShader = noop;61 stub.disable = noop;62 stub.disableVertexAttribArray = noop;63 stub.drawArrays = noop;64 stub.drawElements = noop;65 stub.enable = noop;66 stub.enableVertexAttribArray = noop;67 stub.finish = noop;68 stub.flush = noop;69 stub.framebufferRenderbuffer = noop;70 stub.framebufferTexture2D = noop;71 stub.frontFace = noop;72 stub.generateMipmap = noop;73 stub.getActiveAttrib = getStub;74 stub.getActiveUniform = getStub;75 stub.getAttachedShaders = getStubWarning;76 stub.getAttribLocation = getStub;77 stub.getBufferParameter = getStubWarning;78 stub.getContextAttributes = getContextAttributesStub(options);79 stub.getError = getErrorStub;80 stub.getExtension = getExtensionStub;81 stub.getFramebufferAttachmentParameter = getStubWarning;82 stub.getParameter = getParameterStub(options);83 stub.getProgramParameter = getProgramParameterStub;84 stub.getProgramInfoLog = getStub;85 stub.getRenderbufferParameter = getStubWarning;86 stub.getShaderParameter = getShaderParameterStub;87 stub.getShaderInfoLog = getStub;88 stub.getShaderPrecisionFormat = getShaderPrecisionStub;89 stub.getShaderSource = getStubWarning;90 stub.getSupportedExtensions = getStubWarning;91 stub.getTexParameter = getStubWarning;92 stub.getUniform = getStub;93 stub.getUniformLocation = getStub;94 stub.getVertexAttrib = getStubWarning;95 stub.getVertexAttribOffset = getStubWarning;96 stub.hint = noop;97 stub.isBuffer = getStubWarning;98 stub.isContextLost = getStubWarning;99 stub.isEnabled = getStubWarning;100 stub.isFramebuffer = getStubWarning;101 stub.isProgram = getStubWarning;102 stub.isRenderbuffer = getStubWarning;103 stub.isShader = getStubWarning;104 stub.isTexture = getStubWarning;105 stub.lineWidth = noop;106 stub.linkProgram = noop;107 stub.pixelStorei = noop;108 stub.polygonOffset = noop;109 stub.readPixels = readPixelsStub;110 stub.renderbufferStorage = noop;111 stub.sampleCoverage = noop;112 stub.scissor = noop;113 stub.shaderSource = noop;114 stub.stencilFunc = noop;115 stub.stencilFuncSeparate = noop;116 stub.stencilMask = noop;117 stub.stencilMaskSeparate = noop;118 stub.stencilOp = noop;119 stub.stencilOpSeparate = noop;120 stub.texParameterf = noop;121 stub.texParameteri = noop;122 stub.texImage2D = noop;123 stub.texSubImage2D = noop;124 stub.uniform1f = noop;125 stub.uniform1fv = noop;126 stub.uniform1i = noop;127 stub.uniform1iv = noop;128 stub.uniform2f = noop;129 stub.uniform2fv = noop;130 stub.uniform2i = noop;131 stub.uniform2iv = noop;132 stub.uniform3f = noop;133 stub.uniform3fv = noop;134 stub.uniform3i = noop;135 stub.uniform3iv = noop;136 stub.uniform4f = noop;137 stub.uniform4fv = noop;138 stub.uniform4i = noop;139 stub.uniform4iv = noop;140 stub.uniformMatrix2fv = noop;141 stub.uniformMatrix3fv = noop;142 stub.uniformMatrix4fv = noop;143 stub.useProgram = noop;144 stub.validateProgram = noop;145 stub.vertexAttrib1f = noop;146 stub.vertexAttrib1fv = noop;147 stub.vertexAttrib2f = noop;148 stub.vertexAttrib2fv = noop;149 stub.vertexAttrib3f = noop;150 stub.vertexAttrib3fv = noop;151 stub.vertexAttrib4f = noop;152 stub.vertexAttrib4fv = noop;153 stub.vertexAttribPointer = noop;154 stub.viewport = noop;155 return stub;156 }157 function noop() {158 }159 function createStub() {160 return {};161 }162 function getStub() {163 return {};164 }165 function getStubWarning() {166 //>>includeStart('debug', pragmas.debug);167 throw new DeveloperError('A stub for this get/is function is not defined. Can it use getStub() or does it need a new one?');168 //>>includeEnd('debug');169 }170 function checkFramebufferStatusStub(target) {171 return WebGLConstants.FRAMEBUFFER_COMPLETE;172 }173 function getContextAttributesStub(options) {174 var contextAttributes = {175 alpha : defaultValue(options.alpha, true),176 depth : defaultValue(options.depth, true),177 stencil : defaultValue(options.stencil, false),178 antialias : defaultValue(options.antialias, true),179 premultipliedAlpha : defaultValue(options.premultipliedAlpha, true),180 preserveDrawingBuffer : defaultValue(options.preserveDrawingBuffer, false),181 powerPreference : defaultValue(options.powerPreference, false),182 failIfMajorPerformanceCaveat : defaultValue(options.failIfMajorPerformanceCaveat, false)183 };184 return function() {185 return contextAttributes;186 };187 }188 function getErrorStub() {189 return WebGLConstants.NO_ERROR;190 }191 function getExtensionStub(name) {192 // No extensions are stubbed.193 return null;194 }195 function getParameterStub(options) {196 // These are not the minimum maximum; instead, they are typical maximums.197 var parameterStubValues = {};198 parameterStubValues[WebGLConstants.STENCIL_BITS] = options.stencil ? 8 : 0;199 parameterStubValues[WebGLConstants.MAX_COMBINED_TEXTURE_IMAGE_UNITS] = 32;200 parameterStubValues[WebGLConstants.MAX_CUBE_MAP_TEXTURE_SIZE] = 16384;201 parameterStubValues[WebGLConstants.MAX_FRAGMENT_UNIFORM_VECTORS] = 1024;202 parameterStubValues[WebGLConstants.MAX_TEXTURE_IMAGE_UNITS] = 16;203 parameterStubValues[WebGLConstants.MAX_RENDERBUFFER_SIZE] = 16384;204 parameterStubValues[WebGLConstants.MAX_TEXTURE_SIZE] = 16384;205 parameterStubValues[WebGLConstants.MAX_VARYING_VECTORS] = 30;206 parameterStubValues[WebGLConstants.MAX_VERTEX_ATTRIBS] = 16;207 parameterStubValues[WebGLConstants.MAX_VERTEX_TEXTURE_IMAGE_UNITS] = 16;208 parameterStubValues[WebGLConstants.MAX_VERTEX_UNIFORM_VECTORS] = 4096;209 parameterStubValues[WebGLConstants.ALIASED_LINE_WIDTH_RANGE] = [1, 1];210 parameterStubValues[WebGLConstants.ALIASED_POINT_SIZE_RANGE] = [1, 1024];211 parameterStubValues[WebGLConstants.MAX_VIEWPORT_DIMS] = [16384, 16384];212 parameterStubValues[WebGLConstants.MAX_TEXTURE_MAX_ANISOTROPY_EXT] = 16; // Assuming extension213 parameterStubValues[WebGLConstants.MAX_DRAW_BUFFERS] = 8; // Assuming extension214 parameterStubValues[WebGLConstants.MAX_COLOR_ATTACHMENTS] = 8; // Assuming extension215 return function(pname) {216 var value = parameterStubValues[pname];217 //>>includeStart('debug', pragmas.debug);218 if (!defined(value)) {219 throw new DeveloperError('A WebGL parameter stub for ' + pname + ' is not defined. Add it.');220 }221 //>>includeEnd('debug');222 return value;223 };224 }225 function getProgramParameterStub(program, pname) {226 if ((pname === WebGLConstants.LINK_STATUS) || (pname === WebGLConstants.VALIDATE_STATUS)) {227 return true;228 }229 if ((pname === WebGLConstants.ACTIVE_UNIFORMS) || (pname === WebGLConstants.ACTIVE_ATTRIBUTES)) {230 return 0;231 }232 //>>includeStart('debug', pragmas.debug);233 throw new DeveloperError('A WebGL parameter stub for ' + pname + ' is not defined. Add it.');234 //>>includeEnd('debug');235 }236 function getShaderParameterStub(shader, pname) {237 //>>includeStart('debug', pragmas.debug);238 if (pname !== WebGLConstants.COMPILE_STATUS) {239 throw new DeveloperError('A WebGL parameter stub for ' + pname + ' is not defined. Add it.');240 }241 //>>includeEnd('debug');242 return true;243 }244 function getShaderPrecisionStub(shadertype, precisiontype) {245 //>>includeStart('debug', pragmas.debug);246 if (shadertype !== WebGLConstants.FRAGMENT_SHADER) {247 throw new DeveloperError('getShaderPrecision only has a stub for FRAGMENT_SHADER. Update it.');248 }249 if ((precisiontype !== WebGLConstants.HIGH_FLOAT) && (precisiontype !== WebGLConstants.HIGH_INT)) {250 throw new DeveloperError('getShaderPrecision only has a stub for HIGH_FLOAT and HIGH_INT. Update it.');251 }252 //>>includeEnd('debug');253 if (precisiontype === WebGLConstants.HIGH_FLOAT) {254 return {255 rangeMin : 127,256 rangeMax : 127,257 precision : 23258 };259 }260 // HIGH_INT261 return {262 rangeMin : 31,263 rangeMax : 30,264 precision : 0265 };266 }267 function readPixelsStub(x, y, width, height, format, type, pixels) {268 return [0, 0, 0, 0];269 }270 return getWebGLStub;...

Full Screen

Full Screen

roles-init.helper.unit.js

Source:roles-init.helper.unit.js Github

copy

Full Screen

...75 const childrenRoleTreeChildNames = [ 'child', 'child2' ];76 let createInitialRoleStub;77 let createInitialRolesStub;78 beforeEach(() => {79 createInitialRoleStub = sinon.stub(rolesInitHelper, 'createInitialRole');80 createInitialRolesStub = sinon.stub(rolesInitHelper, 'createInitialRoles').callThrough();81 });82 afterEach(() => {83 createInitialRoleStub.restore();84 createInitialRolesStub.restore();85 });86 it('should return a promise', () => {87 createInitialRoleStub.resolves();88 rolesInitHelper.createInitialRoles(singleRoleTree).constructor.name.should.equal('Promise');89 });90 it('should call createInitalRole with the root of the tree', () => {91 createInitialRoleStub.resolves();92 return rolesInitHelper.createInitialRoles(singleRoleTree).then(() => {93 createInitialRoleStub.args.should.deep.equal([[94 singleRoleTree.name,95 null,96 [],97 singleRoleTree.permissions98 ]]);99 });100 });101 it('should call createInitialRole with child names if they exist', () => {102 createInitialRoleStub.resolves();103 // the first call is the test, dont care about the others104 createInitialRolesStub.onCall(1).resolves();105 createInitialRolesStub.onCall(2).resolves();106 107 return rolesInitHelper.createInitialRoles(childrenRoleTree).then(() => {108 createInitialRoleStub.args[0].should.deep.equal([109 childrenRoleTree.name,110 null,111 childrenRoleTreeChildNames,112 undefined113 ]);114 });115 });116 it('should call createInitialRoles with its children if they exist', () => {117 createInitialRoleStub.resolves();118 119 createInitialRolesStub.onCall(1).resolves();120 createInitialRolesStub.onCall(2).resolves();121 return rolesInitHelper.createInitialRoles(childrenRoleTree).then(() => {122 createInitialRolesStub.args.should.deep.equal([[123 childrenRoleTree124 ], [125 childrenRoleTree.children[0],126 childrenRoleTree.name127 ], [128 childrenRoleTree.children[1],129 childrenRoleTree.name130 ]]);131 });132 });133 });134 describe('#createInitialRole', () => {135 let countStub, execStub, saveStub, isRouteAllowedStub, getEndpointHashStub, pruneEndpointDetailsStub;136 beforeEach(() => {137 execStub = sinon.stub();138 countStub = sinon.stub(Roles, 'count');139 saveStub = sinon.stub(Roles.prototype, 'save');140 isRouteAllowedStub = sinon.stub(rolesInitHelper, 'isRouteAllowed');141 getEndpointHashStub = sinon.stub(roleManager, 'getEndpointHash');142 pruneEndpointDetailsStub = sinon.stub(roleManager, 'pruneEndpointDetails');143 });144 afterEach(() => {145 countStub.restore();146 saveStub.restore();147 isRouteAllowedStub.restore();148 getEndpointHashStub.restore();149 pruneEndpointDetailsStub.restore();150 });151 function setupAllResolve() {152 setupCountResolves();153 setupSaveResolves();154 setupIsRouteAllowedResolves();155 setupGetEndpointHashResolves();156 setupPruneEndpointDetailsResolves();157 }158 function setupCountResolves() {159 countStub.returns({ exec: execStub });160 execStub.resolves(0);161 }162 function setupSaveResolves() {163 saveStub.resolves(mockRole);164 }165 function setupGetEndpointHashResolves() {166 getEndpointHashStub.returns('hash');167 }168 function setupPruneEndpointDetailsResolves() {169 pruneEndpointDetailsStub.returns('pruned');170 }171 function setupIsRouteAllowedResolves() {172 isRouteAllowedStub.returns(true);173 }174 it('should call isRouteAllowed for each route in a module specified in config', () => {175 setupAllResolve();176 const permissions = [177 {178 module: 'test',179 allow: [],180 forbid: []181 },182 {183 module: 'test2',184 allow: [],185 forbid: []186 }187 ];188 rolesInitHelper.createInitialRole('name', null, undefined, permissions);189 isRouteAllowedStub.args.should.deep.equal([[190 mockRoutes[permissions[0].module][0],191 permissions[0].allow,192 permissions[0].forbid193 ], [194 mockRoutes[permissions[0].module][1],195 permissions[0].allow,196 permissions[0].forbid197 ], [198 mockRoutes[permissions[1].module][0],199 permissions[1].allow,200 permissions[1].forbid201 ]]);202 });203 it('should throw an error if a config module does not exist', () => {204 setupAllResolve();205 const permissions = [206 {207 module: 'idontexist',208 allow: [],209 forbid: []210 }211 ];212 should.throw(() => {213 rolesInitHelper.createInitialRole('name', null, undefined, permissions)214 });215 });216 it('should use get the hash of each allowed endpoint', () => {217 setupAllResolve();218 const permissions = [219 {220 module: 'test',221 allow: [],222 forbid: []223 }224 ];225 rolesInitHelper.createInitialRole('name', null, undefined, permissions);226 pruneEndpointDetailsStub.args.should.deep.equal([[227 mockRoutes[permissions[0].module][0],228 ], [229 mockRoutes[permissions[0].module][1]230 ]]);231 getEndpointHashStub.args.should.deep.equal([[ 'pruned' ], [ 'pruned' ]]);232 });233 it('should return a promise', () => {234 setupAllResolve();235 rolesInitHelper.createInitialRole('name', null).constructor.name.should.equal('Promise');236 });237 it('should use Roles.count', () => {238 setupAllResolve();239 rolesInitHelper.createInitialRole('name', null).then((data) => {240 countStub.args.should.deep.equal([[ { _id: 'name', parent: null } ]]);241 execStub.called.should.equal(true);242 });243 });244 it('should use the save stub if count is 0', () => {245 setupAllResolve();246 rolesInitHelper.createInitialRole('name', null).then((data) => {247 saveStub.called.should.equal(true);248 });249 });250 it('should not use the save stub if count is not 0', () => {251 countStub.returns({ exec: execStub });252 execStub.resolves(1);253 rolesInitHelper.createInitialRole('name', null).then((data) => {254 saveStub.called.should.equal(false);255 });256 });257 });258 describe('#isRouteAllowed', () => {259 const route = {260 type: 'GET',261 route: '/test'262 };263 let allow = [];264 let forbid = [];265 266 const routeString = 'GET/test';267 let containsMatchStub;268 beforeEach(() => {269 containsMatchStub = sinon.stub(rolesInitHelper, 'containsMatch');270 });271 afterEach(() => {272 containsMatchStub.restore();273 });274 it('should call containsMatch with the allow list then the forbid list', () => {275 allow = [ 'a', /b/ ];276 forbid = [ /c/ ];277 // dont really care for this test278 containsMatchStub.returns(true);279 rolesInitHelper.isRouteAllowed(route, allow, forbid);280 containsMatchStub.args.should.deep.equal([281 [ routeString, allow ],282 [ routeString, forbid ]283 ]);284 });285 it('should return true if the route is explicitly allowed', () => {286 containsMatchStub.onCall(0).returns(true);287 containsMatchStub.onCall(1).returns(false);288 rolesInitHelper.isRouteAllowed(route, allow, forbid).should.equal(true);289 });290 it('should return false if the route is not explicitly allowed or forbidden', () => {291 containsMatchStub.onCall(0).returns(false);292 containsMatchStub.onCall(1).returns(true);293 rolesInitHelper.isRouteAllowed(route, allow, forbid).should.equal(false);294 });295 it('should return false if the route is explicitly allowed and forbidden', () => {296 containsMatchStub.onCall(0).returns(true);297 containsMatchStub.onCall(1).returns(true);298 rolesInitHelper.isRouteAllowed(route, allow, forbid).should.equal(false);299 });300 });301 describe('#containsMatch', () => {302 const routeString = 'GET/test';303 let postRegExp = /POST.*/;304 let getRegExp = /GET.*/;305 let deleteRegExp = /DELETE.*/;306 let regExps = [307 postRegExp,308 getRegExp,309 deleteRegExp310 ];311 it('should return false if expressions is empty', () => {312 rolesInitHelper.containsMatch(routeString, []).should.equal(false);313 });314 it('should return true if a string equals the routeString', () => {315 rolesInitHelper.containsMatch(routeString, [ 'GET/test' ]).should.equal(true);316 });317 it('should return true if a RegExp tests equal to the routeString', () => {318 rolesInitHelper.containsMatch(routeString, [ /GET.*/ ]).should.equal(true);319 });320 it('should throw an error if a different type is passed in the expressions list', () => {321 should.throw(() => { rolesInitHelper.containsMatch(routeString, [ 0 ])});322 });323 it('should test each element until it finds a match', () => {324 testPostStub = sinon.stub(postRegExp, 'test').returns(false);325 testGetStub = sinon.stub(getRegExp, 'test').returns(true);326 testDeleteSpy = sinon.spy(deleteRegExp, 'test');327 rolesInitHelper.containsMatch(routeString, regExps).should.equal(true);328 testPostStub.called.should.equal(true);329 testGetStub.called.should.equal(true);330 testDeleteSpy.called.should.equal(false);331 testPostStub.restore();332 testGetStub.restore();333 testDeleteSpy.restore();334 });335 });...

Full Screen

Full Screen

Binding.js

Source:Binding.js Github

copy

Full Screen

1/**2 * This class is created to manage a direct bind. Both `Ext.data.Session`3 * and `Ext.app.ViewModel` return these objects from their `bind` method.4 */5Ext.define('Ext.app.bind.Binding', {6 extend: 'Ext.app.bind.BaseBinding',7 /**8 * @cfg {Boolean} [deep=false]9 * Normally a binding is only notified of changes to its bound property, but if that10 * property is an object it is sometimes helpful to be notified of changes to its11 * properties. To receive notifications of changes to all properties of a bound object,12 * set this to `true`.13 * @since 5.0.014 */15 constructor: function (stub, callback, scope, options) {16 var me = this;17 me.callParent([ stub.owner, callback, scope, options ]);18 me.stub = stub;19 me.depth = stub.depth;20 // We need to announce the current value, so if the stub is not loading (which21 // will generate its own announcement to all bindings) then we need to schedule22 // ourselves.23 if (!stub.isLoading() && !stub.scheduled) {24 me.schedule();25 }26 },27 /**28 * Destroys this binding. No further calls will be made to the callback method. No29 * methods should be called on this binding after calling this method.30 * @since 5.0.031 */32 destroy: function (/* private */ fromParent) {33 var me = this,34 stub = me.stub;35 if (stub && !fromParent) {36 stub.unbind(me);37 me.stub = null;38 }39 me.callParent();40 },41 /**42 * Binds to the `validation` association for the bound property. For example, when a43 * binding is bound to something like this:44 *45 * var binding = viewModel.bind('{theUser.name}', ...);46 *47 * The validation status for the "name" property can be requested like so:48 *49 * var validationBinding = binding.bindValidation(fn, scope);50 *51 * Calling this method in the above example would be equivalent to the following bind:52 *53 * var validationBinding = viewModel.bind('{theUser.validation.name}', fn, scope);54 *55 * The primary reason to use this method is in cases where the original bind expression56 * is not known.57 *58 * For example, this method is used by `Ext.form.field.Base` when given the59 * `{@link Ext.Component#modelValidation modelValidation}` config is set. As such it60 * not common for users to need to call this method.61 *62 * @param {Function} callback The function to call when the validation changes.63 * @param {Object} [scope] The scope on which to call the `callback`.64 * @return {Ext.app.bind.Binding} A binding to the validation of the bound property.65 * @since 5.0.066 */67 bindValidation: function (callback, scope) {68 var stub = this.stub;69 return stub && stub.bindValidation(callback, scope);70 },71 /**72 * Bind to a model field for validation73 * @param {Function/String} callback The function to call or the name of the function on the scope74 * @param {Object} scope The scope for the callback75 * @return {Ext.app.bind.Binding} The binding, if available76 *77 * @private78 */79 bindValidationField: function(callback, scope) {80 var stub = this.stub;81 return stub && stub.bindValidationField(callback, scope);82 },83 /**84 * Returns the diagnostic name for this binding.85 * @return {String}86 * @since 5.0.087 */88 getFullName: function () {89 return this.fullName || (this.fullName = '@(' + this.stub.getFullName() + ')');90 },91 /**92 * Returns the current value of the bound property. If this binding `isLoading` this93 * value will be `undefined`.94 * @return {Mixed} The value of the bound property.95 * @since 5.0.096 */97 getValue: function () {98 var me = this,99 stub = me.stub,100 ret = stub && stub.getValue();101 if (me.transform) {102 ret = me.transform(ret);103 }104 return ret;105 },106 /**107 * Returns `true` if the bound property is loading. In the general case this means108 * that the value is just not available yet. In specific cases, when the bound property109 * is an `Ext.data.Model` it means that a request to the server is in progress to get110 * the record. For an `Ext.data.Store` it means that111 * `{@link Ext.data.Store#load load}` has been called on the store but it is112 * still in progress.113 * @return {Boolean}114 * @since 5.0.0115 */116 isLoading: function () {117 var stub = this.stub;118 return stub && stub.isLoading();119 },120 /**121 * This method returns `true` if this binding can only be read. If this method returns122 * `false` then the binding can be set using `setValue` (meaning this binding can be123 * a two-way binding).124 * @return {boolean}125 * @since 5.0.0126 */127 isReadOnly: function () {128 var stub = this.stub,129 options = this.options;130 if (!(options && options.twoWay === false)) {131 if (stub) {132 return stub.isReadOnly();133 }134 }135 return true; // readOnly so just one-way136 },137 /**138 * Tells the bound property to refresh itself. This has meaning when the bound property139 * is something like an `Ext.data.Model` and an `Ext.data.Store` but does nothing in140 * most cases.141 * @since 5.0.0142 */143 refresh: function () {144 //TODO - maybe nothing to do here but entities/stores would have work to do145 },146 /**147 * Sets the value of the bound property. This will throw an error in debug mode if148 * this binding `isReadOnly`.149 * @param {Mixed} value The new value.150 * @since 5.0.0151 */152 setValue: function (value) {153 //<debug>154 if (this.isReadOnly()) {155 Ext.raise('Cannot setValue on a readonly binding');156 }157 //</debug>158 this.stub.set(value);159 },160 privates: {161 getDataObject: function () {162 var stub = this.stub;163 return stub && stub.getDataObject();164 },165 getRawValue: function () {166 var me = this,167 stub = me.stub,168 ret = stub && stub.getRawValue();169 if (me.transform) {170 ret = me.transform(ret);171 }172 return ret;173 },174 isDescendantOf: function (item) {175 var stub = this.stub;176 return stub ? (item === stub) || stub.isDescendantOf(item) : false;177 },178 react: function () {179 this.notify(this.getValue());180 },181 schedule: function() {182 // If the parent stub is already scheduled, then we will be183 // called when the stub hits the next tick.184 if (!this.stub.scheduled) {185 this.callParent();186 }187 },188 189 sort: function () {190 var stub = this.stub;191 stub.scheduler.sortItem(stub);192 // Schedulable#sort === emptyFn193 //me.callParent();194 }195 }...

Full Screen

Full Screen

productDecoratorsMock.js

Source:productDecoratorsMock.js Github

copy

Full Screen

1'use strict';2var proxyquire = require('proxyquire').noCallThru().noPreserveCache();3var sinon = require('sinon');4var stubBase = sinon.stub();5var stubPrice = sinon.stub();6var stubImages = sinon.stub();7var stubAvailability = sinon.stub();8var stubDescription = sinon.stub();9var stubSearchPrice = sinon.stub();10var stubPromotions = sinon.stub();11var stubQuantity = sinon.stub();12var stubQuantitySelector = sinon.stub();13var stubRatings = sinon.stub();14var stubSizeChart = sinon.stub();15var stubVariationAttributes = sinon.stub();16var stubSearchVariationAttributes = sinon.stub();17var stubAttributes = sinon.stub();18var stubOptions = sinon.stub();19var stubCurrentUrl = sinon.stub();20var stubReadyToOrder = sinon.stub();21var stubOnline = sinon.stub();22var stubSetReadyToOrder = sinon.stub();23var stubBundleReadyToOrder = sinon.stub();24var stubSetIndividualProducts = sinon.stub();25var stubSetProductsCollection = sinon.stub();26var stubBundledProducts = sinon.stub();27var stubBonusUnitPrice = sinon.stub();28var stubRaw = sinon.stub();29var stubPageMetaData = sinon.stub();30var stubTemplate = sinon.stub();31function proxyModel() {32 return {33 mocks: proxyquire('../../cartridges/app_storefront_base/cartridge/models/product/decorators/index', {34 '*/cartridge/models/product/decorators/base': stubBase,35 '*/cartridge/models/product/decorators/availability': stubAvailability,36 '*/cartridge/models/product/decorators/description': stubDescription,37 '*/cartridge/models/product/decorators/images': stubImages,38 '*/cartridge/models/product/decorators/price': stubPrice,39 '*/cartridge/models/product/decorators/searchPrice': stubSearchPrice,40 '*/cartridge/models/product/decorators/promotions': stubPromotions,41 '*/cartridge/models/product/decorators/quantity': stubQuantity,42 '*/cartridge/models/product/decorators/quantitySelector': stubQuantitySelector,43 '*/cartridge/models/product/decorators/ratings': stubRatings,44 '*/cartridge/models/product/decorators/sizeChart': stubSizeChart,...

Full Screen

Full Screen

RootStub.js

Source:RootStub.js Github

copy

Full Screen

1/**2 * This class is the root stub for managing a `ViewModel`.3 * @private4 */5Ext.define('Ext.app.bind.RootStub', {6 extend: 'Ext.app.bind.AbstractStub',7 requires: [8 'Ext.app.bind.LinkStub',9 'Ext.app.bind.Stub'10 ],11 isRootStub: true,12 13 depth: 0,14 createRootChild: function (name, direct) {15 var me = this,16 owner = me.owner,17 ownerData = owner.getData(),18 children = me.children,19 previous = children && children[name],20 parentStub = previous ? null : me,21 parentVM, stub;22 if (direct || ownerData.hasOwnProperty(name) || !(parentVM = owner.getParent())) {23 stub = new Ext.app.bind.Stub(owner, name, parentStub);24 } else {25 stub = new Ext.app.bind.LinkStub(owner, name, previous ? null : parentStub);26 stub.link('{' + name + '}', parentVM);27 }28 if (previous) {29 previous.graft(stub);30 }31 return stub;32 },33 34 createStubChild: function(name) {35 return this.createRootChild(name, true);36 },37 descend: function (path, index) {38 var me = this,39 children = me.children,40 pos = index || 0,41 name = path[pos++],42 ret = (children && children[name]) || me.createRootChild(name);43 if (pos < path.length) {44 ret = ret.descend(path, pos);45 }46 return ret;47 },48 getFullName: function () {49 return this.fullName || (this.fullName = this.owner.id + ':');50 },51 // The root Stub is associated with the owner's "data" object52 getDataObject: function () {53 return this.owner.data;54 },55 getRawValue: function () {56 return this.owner.data;57 },58 getValue: function () {59 return this.owner.data;60 },61 isDescendantOf: function () {62 return false;63 },64 isLoading: function () {65 return false;66 },67 set: function (value) {68 //<debug>69 if (!value || value.constructor !== Object) {70 Ext.raise('Only an object can be set at the root');71 }72 //</debug>73 var me = this,74 children = me.children || (me.children = {}),75 owner = me.owner,76 data = owner.data,77 parentVM = owner.getParent(),78 linkStub, stub, v, key;79 for (key in value) {80 //<debug>81 if (key.indexOf('.') >= 0) {82 Ext.raise('Value names cannot contain dots');83 }84 //</debug>85 if ((v = value[key]) !== undefined) {86 if (!(stub = children[key])) {87 stub = new Ext.app.bind.Stub(owner, key, me);88 } else if (stub.isLinkStub) {89 if (!stub.getLinkFormulaStub()) {90 // Pass parent=null since we will graft in this new stub to replace us:91 linkStub = stub;92 stub = new Ext.app.bind.Stub(owner, key);93 linkStub.graft(stub);94 }95 }96 stub.set(v);97 } else if (data.hasOwnProperty(key)) {98 delete data[key];99 stub = children[key];100 if (stub && !stub.isLinkStub && parentVM) {101 stub = me.createRootChild(key);102 }103 stub.invalidate(true);104 }105 }106 },107 schedule: Ext.emptyFn,108 109 unschedule: Ext.emptyFn...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var sinon = require('sinon');2var chai = require('chai');3var expect = chai.expect;4var sinonChai = require('sinon-chai');5chai.use(sinonChai);6var myModule = require('./myModule');7describe('myModule', function () {8 describe('myMethod', function () {9 it('should call myOtherMethod', function () {10 var stub = sinon.stub(myModule, 'myOtherMethod');11 myModule.myMethod();12 expect(stub).to.have.been.called;13 stub.restore();14 });15 });16});17exports.myMethod = function () {18 this.myOtherMethod();19};20exports.myOtherMethod = function () {21 console.log('myOtherMethod called');22};

Full Screen

Using AI Code Generation

copy

Full Screen

1var sinon = require('sinon');2var assert = require('assert');3var stub = sinon.stub();4stub.withArgs(42).returns(1);5stub.withArgs(43).throws("TypeError");6assert.equal(stub(42), 1);7assert.throws(function(){ stub(43); }, "TypeError");8var sinon = require('sinon');9var assert = require('assert');10var mock = sinon.mock();11mock.expects("foo").once().withArgs(42).returns(1);12mock.expects("foo").once().withArgs(43).throws("TypeError");13assert.equal(mock.foo(42), 1);14assert.throws(function(){ mock.foo(43); }, "TypeError");15mock.verify();16var sinon = require('sinon');17var assert = require('assert');18var spy = sinon.spy();19spy(42);20assert(spy.calledOnce);21assert(spy.calledWith(42));22var sinon = require('sinon');23var assert = require('assert');24var fake = sinon.fake();25fake(42);26assert(fake.calledOnce);27assert(fake.calledWith(42));28var sinon = require('sinon');29var assert = require('assert');30var server = sinon.fakeServer.create();31server.respondWith("GET", "/echo", [200, { "Content-Type": "application/json" }, '{ "echo": "Hello World!" }']);32server.respond();33var sinon = require('sinon');34var assert = require('assert');35var clock = sinon.useFakeTimers();36var callback = sinon.spy();37var interval = setInterval(callback, 1000);38clock.tick(1000);39assert(callback.calledOnce);40clock.tick(1000);41assert(callback.calledTwice);42clearInterval(interval);43clock.restore();44var sinon = require('sinon');45var assert = require('assert');46var clock = sinon.useFakeTimers();47var callback = sinon.spy();48var timeout = setTimeout(callback, 1000);49clock.tick(1000);50assert(callback.calledOnce);51clearTimeout(timeout);52clock.restore();53var sinon = require('sinon');54var assert = require('assert');

Full Screen

Using AI Code Generation

copy

Full Screen

1var sinon = require('sinon');2var assert = require('assert');3var myModule = require('./myModule.js');4var stub = sinon.stub(myModule, 'myMethod');5stub.yields(null, 'hello');6myModule.myMethod(function(err, data) {7});8assert(stub.calledOnce);9module.exports = {10 myMethod: function(callback) {11 callback(null, 'hello');12 }13};14var sinon = require('sinon');15var assert = require('assert');16var myModule = require('./myModule.js');17var stub = sinon.stub(myModule, 'myMethod');18stub.yields(null, 'hello');19myModule.myMethod(function(err, data) {20});21assert(stub.calledOnce);22var request = require('request');23module.exports = {24 myMethod: function(callback) {25 callback(null, 'hello');26 });27 }28};29var sinon = require('sinon');30var assert = require('assert');31var myModule = require('./myModule.js');32var stub = sinon.stub(myModule, 'myMethod');33stub.yields(null, 'hello');34myModule.myMethod(function(err, data) {35});36assert(stub.calledOnce);37var request = require('request');38module.exports = {39 myMethod: function(callback) {40 callback(null, 'hello');41 });42 }43};

Full Screen

Using AI Code Generation

copy

Full Screen

1var stub = sinon.stub(obj, 'method', function() { return 'stubbed'; });2var mock = sinon.mock(obj).expects('method').once().returns('mocked');3var spy = sinon.spy(obj, 'method');4var server = sinon.fakeServer.create();5var clock = sinon.useFakeTimers();6var xhr = sinon.useFakeXMLHttpRequest();7var sandbox = sinon.sandbox.create();8sinon.assert.calledOnce(obj.method);9sinon.match.number.test(3);10sinon.format(obj.method);11sinon.create(obj.method);12sinon.clock.now;13sinon.fakeServer.xhr;14sinon.fakeXhr.xhr;15sinon.sandbox.xhr;16sinon.assert.calledOnce(obj.method);17sinon.match.number.test(3);18sinon.format(obj.method);19sinon.create(obj.method);20sinon.clock.now;21sinon.fakeServer.xhr;22sinon.fakeXhr.xhr;23sinon.sandbox.xhr;24sinon.assert.calledOnce(obj.method);25sinon.match.number.test(3);26sinon.format(obj.method);27sinon.create(obj.method);28sinon.clock.now;29sinon.fakeServer.xhr;

Full Screen

Using AI Code Generation

copy

Full Screen

1var stub = sinon.stub(object, 'method');2var spy = sinon.spy(object, 'method');3var mock = sinon.mock(object);4var stub = sinon.stub(object, 'method');5var spy = sinon.spy(object, 'method');6var mock = sinon.mock(object);7var stub = sinon.stub(object, 'method');8var spy = sinon.spy(object, 'method');9var mock = sinon.mock(object);10var stub = sinon.stub(object, 'method');11var spy = sinon.spy(object, 'method');12var mock = sinon.mock(object);13var stub = sinon.stub(object, 'method');14var spy = sinon.spy(object, 'method');15var mock = sinon.mock(object);16var stub = sinon.stub(object, 'method');17var spy = sinon.spy(object, 'method');18var mock = sinon.mock(object);19var stub = sinon.stub(object, 'method');20var spy = sinon.spy(object, 'method');21var mock = sinon.mock(object);22var stub = sinon.stub(object, 'method');23var spy = sinon.spy(object, 'method');24var mock = sinon.mock(object);

Full Screen

Using AI Code Generation

copy

Full Screen

1var sinon = require('sinon');2var assert = require('assert');3var myFunc = require('./myFunc');4var myObj = require('./myObj');5var stub = sinon.stub(myObj, 'myFunc');6stub.withArgs(1).returns('one');7stub.withArgs(2).returns('two');8assert.equal(myFunc(1), 'one');9assert.equal(myFunc(2), 'two');10var myObj = require('./myObj');11function myFunc(n) {12 return myObj.myFunc(n);13}14module.exports = myFunc;15function myFunc(n) {16 if (n === 1) {17 return 'one';18 }19 if (n === 2) {20 return 'two';21 }22}23module.exports.myFunc = myFunc;24I want to stub the myObj.myFunc() method with Sinon in my test.js file. I want to stub the method with two different return values for two different arguments. How can I do this? I am using mocha for testing. I have tried the following code, but it doesn't work:Thanks in advance for your help!

Full Screen

Using AI Code Generation

copy

Full Screen

1const stub = sinon.stub(someObject, 'someMethod').resolves('foo')2const stub = sinon.stub(someObject, 'someMethod').rejects('foo')3const stub = sinon.stub(someObject, 'someMethod').callsFake(function () {4})5const stub = sinon.stub(someObject, 'someMethod').resolves('foo')6const stub = sinon.stub(someObject, 'someMethod').rejects('foo')7const stub = sinon.stub(someObject, 'someMethod').callsFake(function () {8})9const stub = sinon.stub(someObject, 'someMethod').resolves('foo')10const stub = sinon.stub(someObject, 'someMethod').rejects('foo')11const stub = sinon.stub(someObject, 'someMethod').callsFake(function () {12})13const stub = sinon.stub(someObject, 'someMethod').resolves('foo')14const stub = sinon.stub(someObject, 'someMethod').rejects('foo')15const stub = sinon.stub(someObject, 'someMethod').callsFake(function () {16})17const stub = sinon.stub(someObject, 'someMethod').resolves('foo')18const stub = sinon.stub(someObject, 'someMethod').rejects('foo')19const stub = sinon.stub(someObject, 'someMethod').callsFake(function () {20})21const stub = sinon.stub(someObject, 'someMethod').resolves('foo')22const stub = sinon.stub(some

Full Screen

Using AI Code Generation

copy

Full Screen

1var sinon = require('sinon');2var assert = require('assert');3var test = require('../lib/test.js');4var testObj = new test();5describe('test', function(){6 it('test', function(done){7 var stub = sinon.stub(testObj, 'test', function(){8 return 'hello';9 });10 assert.equal(testObj.test(), 'hello');11 stub.restore();12 done();13 });14});15var test = function(){16 this.test = function(){17 return 'hello';18 }19}20module.exports = test;21var sinon = require('sinon');22var assert = require('assert');23var test = require('../lib/test.js');24var testObj = new test();25describe('test', function(){26 it('test', function(done){27 var stub = sinon.stub(testObj, 'test', function(){28 return 'hello';29 });30 assert.equal(testObj.test(), 'hello');31 stub.restore();32 done();33 });34});35var test = function(){36 this.test = function(callback){37 callback('hello');38 }39}40module.exports = test;41var sinon = require('sinon');42var assert = require('assert');43var test = require('../lib/test.js');44var testObj = new test();45describe('test', function(){46 it('test', function(done){47 var stub = sinon.stub(testObj, 'test', function(){48 return 'hello';49 });50 assert.equal(testObj.test(), 'hello');51 stub.restore();52 done();53 });54});

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run sinon 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