Best JavaScript code snippet using sinon
spy.js
Source:spy.js  
...52        this.calledTwice = this.callCount == 2;53        this.calledThrice = this.callCount == 3;54    }55    function createCallProperties() {56        this.firstCall = this.getCall(0);57        this.secondCall = this.getCall(1);58        this.thirdCall = this.getCall(2);59        this.lastCall = this.getCall(this.callCount - 1);60    }61    var vars = "a,b,c,d,e,f,g,h,i,j,k,l";62    function createProxy(func) {63        // Retain the function length:64        var p;65        if (func.length) {66            eval("p = (function proxy(" + vars.substring(0, func.length * 2 - 1) +67                ") { return p.invoke(func, this, slice.call(arguments)); });");68        }69        else {70            p = function proxy() {71                return p.invoke(func, this, slice.call(arguments));72            };73        }74        return p;75    }76    var uuid = 0;77    // Public API78    var spyApi = {79        reset: function () {80            this.called = false;81            this.notCalled = true;82            this.calledOnce = false;83            this.calledTwice = false;84            this.calledThrice = false;85            this.callCount = 0;86            this.firstCall = null;87            this.secondCall = null;88            this.thirdCall = null;89            this.lastCall = null;90            this.args = [];91            this.returnValues = [];92            this.thisValues = [];93            this.exceptions = [];94            this.callIds = [];95            if (this.fakes) {96                for (var i = 0; i < this.fakes.length; i++) {97                    this.fakes[i].reset();98                }99            }100        },101        create: function create(func) {102            var name;103            if (typeof func != "function") {104                func = function () { };105            } else {106                name = sinon.functionName(func);107            }108            var proxy = createProxy(func);109            sinon.extend(proxy, spy);110            delete proxy.create;111            sinon.extend(proxy, func);112            proxy.reset();113            proxy.prototype = func.prototype;114            proxy.displayName = name || "spy";115            proxy.toString = sinon.functionToString;116            proxy._create = sinon.spy.create;117            proxy.id = "spy#" + uuid++;118            return proxy;119        },120        invoke: function invoke(func, thisValue, args) {121            var matching = matchingFake(this.fakes, args);122            var exception, returnValue;123            incrementCallCount.call(this);124            push.call(this.thisValues, thisValue);125            push.call(this.args, args);126            push.call(this.callIds, callId++);127            try {128                if (matching) {129                    returnValue = matching.invoke(func, thisValue, args);130                } else {131                    returnValue = (this.func || func).apply(thisValue, args);132                }133                var thisCall = this.getCall(this.callCount - 1);134                if (thisCall.calledWithNew() && typeof returnValue !== 'object') {135                    returnValue = thisValue;136                }137            } catch (e) {138                exception = e;139            }140            push.call(this.exceptions, exception);141            push.call(this.returnValues, returnValue);142            createCallProperties.call(this);143            if (exception !== undefined) {144                throw exception;145            }146            return returnValue;147        },148        getCall: function getCall(i) {149            if (i < 0 || i >= this.callCount) {150                return null;151            }152            return sinon.spyCall(this, this.thisValues[i], this.args[i],153                                    this.returnValues[i], this.exceptions[i],154                                    this.callIds[i]);155        },156        getCalls: function () {157            var calls = [];158            var i;159            for (i = 0; i < this.callCount; i++) {160                calls.push(this.getCall(i));161            }162            return calls;163        },164        calledBefore: function calledBefore(spyFn) {165            if (!this.called) {166                return false;167            }168            if (!spyFn.called) {169                return true;170            }171            return this.callIds[0] < spyFn.callIds[spyFn.callIds.length - 1];172        },173        calledAfter: function calledAfter(spyFn) {174            if (!this.called || !spyFn.called) {175                return false;176            }177            return this.callIds[this.callCount - 1] > spyFn.callIds[spyFn.callCount - 1];178        },179        withArgs: function () {180            var args = slice.call(arguments);181            if (this.fakes) {182                var match = matchingFake(this.fakes, args, true);183                if (match) {184                    return match;185                }186            } else {187                this.fakes = [];188            }189            var original = this;190            var fake = this._create();191            fake.matchingAguments = args;192            fake.parent = this;193            push.call(this.fakes, fake);194            fake.withArgs = function () {195                return original.withArgs.apply(original, arguments);196            };197            for (var i = 0; i < this.args.length; i++) {198                if (fake.matches(this.args[i])) {199                    incrementCallCount.call(fake);200                    push.call(fake.thisValues, this.thisValues[i]);201                    push.call(fake.args, this.args[i]);202                    push.call(fake.returnValues, this.returnValues[i]);203                    push.call(fake.exceptions, this.exceptions[i]);204                    push.call(fake.callIds, this.callIds[i]);205                }206            }207            createCallProperties.call(fake);208            return fake;209        },210        matches: function (args, strict) {211            var margs = this.matchingAguments;212            if (margs.length <= args.length &&213                sinon.deepEqual(margs, args.slice(0, margs.length))) {214                return !strict || margs.length == args.length;215            }216        },217        printf: function (format) {218            var spy = this;219            var args = slice.call(arguments, 1);220            var formatter;221            return (format || "").replace(/%(.)/g, function (match, specifyer) {222                formatter = spyApi.formatters[specifyer];223                if (typeof formatter == "function") {224                    return formatter.call(null, spy, args);225                } else if (!isNaN(parseInt(specifyer, 10))) {226                    return sinon.format(args[specifyer - 1]);227                }228                return "%" + specifyer;229            });230        }231    };232    function delegateToCalls(method, matchAny, actual, notCalled) {233        spyApi[method] = function () {234            if (!this.called) {235                if (notCalled) {236                    return notCalled.apply(this, arguments);237                }238                return false;239            }240            var currentCall;241            var matches = 0;242            for (var i = 0, l = this.callCount; i < l; i += 1) {243                currentCall = this.getCall(i);244                if (currentCall[actual || method].apply(currentCall, arguments)) {245                    matches += 1;246                    if (matchAny) {247                        return true;248                    }249                }250            }251            return matches === this.callCount;252        };253    }254    delegateToCalls("calledOn", true);255    delegateToCalls("alwaysCalledOn", false, "calledOn");256    delegateToCalls("calledWith", true);257    delegateToCalls("calledWithMatch", true);...WebService.js
Source:WebService.js  
...21    *22    * Required params: screenName23    */24    screenNameLookup(screenName, success, failure) {25        this.getCall(URI.LOOKUP_SCREEN_NAME + '/?screenName=' + screenName, success, failure, false);26    }27    /**28    * SignUp Call - User SignUp api call29    * Takes success and failure operations30    *31    * Required params: Name, email, screenName in detail object.32    */33    signUp(details, success, failure) {34        this.postCall(URI.SIGNUP, details, success, failure, false);35    }36    /**37    * Get Profile Call - Get Profile api call38    * Takes success and failure operations39    *40    * Required params: null41    */42    getProfile(success, failure) {43        let user = JSON.parse(localStorage.getItem(AppConstants.USER_FIREBASE_DETAILS));44        this.getCall(URI.GET_PROFILE + '/?email=' + user.email, success, failure, true);45    }46    /**47    * Get Hackathon Call - Get Hackathon api call48    * Takes success and failure operations49    *50    * Required params: null51    */52    getHackathon(role, success, failure) {53        let user = JSON.parse(localStorage.getItem(AppConstants.USER_FIREBASE_DETAILS));54        this.getCall(URI.LIST_HACKATHON + '/?email=' + user.email + '&role=' + role, success, failure, true);55    }56    /**57   * Get Hackathon Call - Get Hackathon api call58   * Takes success and failure operations59   *60   * Required params: null61   */62    getHackathonDetail(eventName, role, success, failure) {63        let user = JSON.parse(localStorage.getItem(AppConstants.USER_FIREBASE_DETAILS));64        this.getCall(URI.DETAIL_HACKATHON + '/?email=' + user.email + '&role=' + role + '&eventName=' + eventName, success, failure, true);65    }66    /**67    * Get Organization List Call - Get Profile api call68    * Takes success and failure operations69    *70    * Required params: null71    */72    getOrganizationList(success, failure) {73        let user = JSON.parse(localStorage.getItem(AppConstants.USER_FIREBASE_DETAILS));74        this.getCall(URI.GET_LIST_ORGANIZATION + '/?email=' + user.email, success, failure, true);75    }76    /**77    * Search Organizations Call - Search Organizations api call78    * Takes success and failure operations79    *80    * Required params: null81    */82    searchOrganization(success, failure) {83        this.getCall(URI.SEARCH_ORGANIZATION + '/?name=' + "", success, failure, true);84    }85    /**86   * Search Organizations Call - Search Organizations api call87   * Takes success and failure operations88   *89   * Required params: null90   */91    fetchEventPrice(email, eventName, success, failure) {92        this.getCall(URI.FETCH_PRICE + '/?email=' + email + "&eventName=" + eventName, success, failure, true);93    }94    /**95    * Update User Profile Call - Update User Profile api call96    * Takes success and failure operations97    *98    * Required params: null99    */100    updateProfile(details, success, failure) {101        this.postCall(URI.UPDATE_PROFILE, details, success, failure, true);102    }103    /**104    * Create Organization Call - Create Organizationapi call105    * Takes success and failure operations106    *107    * Required params: Name, Address, Description108    */109    createOrganization(details, success, failure) {110        this.postCall(URI.CREATE_ORGANIZATION, details, success, failure, true);111    }112    /**113   * Respond Organization Request Call - Respond Organization Request api call114   * Takes success and failure operations115   *116   * Required params: email, isApproved117   */118    respondRequest(details, success, failure) {119        this.postCall(URI.RESPOND_REQUEST, details, success, failure, true);120    }121    /**122   * Create Update Hackathon Request Call - Create Update Hackathon Request api call123   * Takes success and failure operations124   *125   * Required params:126   */127    createUpdateHackathon(details, success, failure) {128        this.postCall(URI.CREATE_UPDATE_HACKATHON, details, success, failure, true);129    }130    /**131   * Create Update Hackathon Request Call - Create Update Hackathon Request api call132   * Takes success and failure operations133   *134   * Required params:135   */136    makePayment(details, success, failure) {137        this.postCall(URI.MAKE_PAYMENT, details, success, failure, true);138    }139    /**140  * Create Update Hackathon Request Call - Create Update Hackathon Request api call141  * Takes success and failure operations142  *143  * Required params:144  */145    registerHackathon(details, success, failure) {146        this.postCall(URI.REGISTER_HACKATHON, details, success, failure, true);147    }148    /**149* Create Update Hackathon Request Call - Create Update Hackathon Request api call150* Takes success and failure operations151*152* Required params:153*/154    submitHackathon(details, success, failure) {155        this.postCall(URI.SUBMIT_HACKATHON, details, success, failure, true);156    }157    saveHackathonGrade(details, success, failure) {158        this.postCall(URI.SAVE_GRADES, details, success, failure, true);159    }160    addExpense(details, success, failure) {161        this.postCall(URI.ADD_EXPENSE, details, success, failure, true);162    }163    fetchLeaderBoard(eventName, success, failure) {164        this.getCall(URI.GET_LEADERBOARD + "?eventName=" + eventName, success, failure, true);165    }166    fetchFinancialReport(email, eventName, success, failure) {167        this.getCall(URI.GET_FINANCIAL_REPORT + "?email=" + email + "&eventName=" + eventName, success, failure, true);168    }...Using AI Code Generation
1var stub = sinon.stub();2stub(1, 2);3var stub = sinon.stub();4stub(1, 2);5var stub = sinon.stub();6stub(1, 2);7var stub = sinon.stub();8stub(1, 2);9var stub = sinon.stub();10stub(1, 2);11var stub = sinon.stub();12stub(1, 2);13var stub = sinon.stub();14stub(1, 2);15var stub = sinon.stub();16stub(1, 2);Using AI Code Generation
1var spy = sinon.spy();2spy();3var stub = sinon.stub();4stub();5var mock = sinon.mock();6mock();7var server = sinon.fakeServer.create();8server.respond();9var xhr = sinon.useFakeXMLHttpRequest();10xhr.respond();Using AI Code Generation
1this.getCall(0).args[0].should.equal('Hello');2this.getCall(0).args[1].should.equal('World');3this.calledWith('Hello', 'World').should.equal(true);4this.calledWithMatch('Hello', /W/).should.equal(true);5this.alwaysCalledWith('Hello', 'World').should.equal(true);6this.alwaysCalledWithMatch('Hello', /W/).should.equal(true);7this.neverCalledWith('Hello', 'World').should.equal(true);8this.neverCalledWithMatch('Hello', /W/).should.equal(true);9this.alwaysCalledOn(this).should.equal(true);10this.calledOn(this).should.equal(true);11this.calledWithNew().should.equal(true);12this.threw().should.equal(true);13this.returned().should.equal(true);14this.alwaysReturned().should.equal(true);15this.callCount.should.equal(1);16this.calledOnce.should.equal(true);17this.calledTwice.should.equal(true);18this.calledThrice.should.equal(true);19this.firstCall.args[0].should.equal('Hello');20this.firstCall.args[1].should.equal('World');21this.secondCall.args[0].should.equal('Hello');22this.secondCall.args[1].should.equal('World');Using AI Code Generation
1this.getCall(0).args[0];2this.getCall(0).args[1];3this.getCall(1).args[0];4this.getCall(1).args[1];5this.getCall(-1).args[0];6this.getCall(-1).args[1];7this.getCall(-2).args[0];8this.getCall(-2).args[1];9this.getCall(-3).args[0];10this.getCall(-3).args[1];11this.getCall(0).args[0];12this.getCall(0).args[1];13this.getCall(1).args[0];14this.getCall(1).args[1];15this.getCall(-Using AI Code Generation
1var spy = sinon.spy();2spy(1, 2, 3);3var firstArg = spy.getCall(0).args[0];4var spy = sinon.spy();5spy(1, 2, 3);6var firstArg = spy.getCall(0).args[0];7var spy = sinon.spy();8spy(1, 2, 3);9var firstArg = spy.getCall(0).args[0];10var spy = sinon.spy();11spy(1, 2, 3);12var firstArg = spy.getCall(0).args[0];13var spy = sinon.spy();14spy(1, 2, 3);15var firstArg = spy.getCall(0).args[0];16var spy = sinon.spy();17spy(1, 2, 3);18var firstArg = spy.getCall(0).args[0];19var spy = sinon.spy();20spy(1, 2, 3);21var firstArg = spy.getCall(0).args[0];22var spy = sinon.spy();23spy(1, 2, 3);24var firstArg = spy.getCall(0).args[0];25var spy = sinon.spy();26spy(1, 2, 3);27var firstArg = spy.getCall(0).args[0];28var spy = sinon.spy();29spy(1,Using AI Code Generation
1var myObject = {2    myMethod: function () {3        console.log("myMethod called");4    },5    myMethod2: function () {6        console.log("myMethod2 called");7    }8};9var mySpy = sinon.spy(myObject, "myMethod");10var mySpy2 = sinon.spy(myObject, "myMethod2");11myObject.myMethod();12myObject.myMethod2();13myObject.myMethod();14console.log(mySpy.getCall(0));15console.log(mySpy.getCall(1));16console.log(mySpy2.getCall(0));17console.log(mySpy2.getCall(1));18console.log(mySpy.getCall(2));19console.log(mySpy2.getCall(2));20Call {thisValue: Object, args: Array[0], returnValue: undefined, exception: null, stack: undefined}21Call {thisValue: Object, args: Array[0], returnValue: undefined, exception: null, stack: undefined}22Call {thisValue: Object, args: Array[0], returnValue: undefined, exception: null, stack: undefined}23Call {thisValue: Object, args: Array[0], returnValue: undefined, exception: null, stack: undefined}24Call {thisValue: Object, args: Array[0], returnValue: undefined, exception: null, stack: undefined}25Call {thisValue: Object, args: Array[0], returnValue: undefined, exception: null, stack: undefined}26Call {thisValue: Object, args: Array[0], returnValue: undefined, exception: null, stack: undefined}27Call {thisValue: Object, args: Array[0], returnValue: undefined, exception: null, stack: undefined}28Call {thisValue: Object, args: Array[0], returnValue: undefined, exception: null, stack: undefined}29Call {thisValue: Object, args: Array[0], returnValue: undefined, exception: null, stack: undefined}30Call {thisValue: Object, args: Array[0], returnValue: undefined, exception: null, stack: undefined}31Call {thisValue: Object, args: Array[0], returnValue: undefined, exception: null, stack: undefined}Using AI Code Generation
1var stub = sinon.stub();2stub.getCall(0);3### getCall(index)4### getCall(index).args5### getCall(index).returnValue6### getCall(index).exception7### getCall(index).thisValue8### getCall(index).calledWithNew9### getCall(index).calledBefore(call)10### getCall(index).calledAfter(call)11### getCall(index).calledWith(...args)12### getCall(index).calledWithExactly(...args)13### getCall(index).notCalledWith(...args)Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
