Best JavaScript code snippet using sinon
SpySpec.js
Source:SpySpec.js  
1describe('Spies', function () {2  it('should replace the specified function with a spy object', function() {3    var originalFunctionWasCalled = false;4    var TestClass = {5      someFunction: function() {6        originalFunctionWasCalled = true;7      }8    };9    this.spyOn(TestClass, 'someFunction');10    expect(TestClass.someFunction.wasCalled).toEqual(false);11    expect(TestClass.someFunction.callCount).toEqual(0);12    TestClass.someFunction('foo');13    expect(TestClass.someFunction.wasCalled).toEqual(true);14    expect(TestClass.someFunction.callCount).toEqual(1);15    expect(TestClass.someFunction.mostRecentCall.args).toEqual(['foo']);16    expect(TestClass.someFunction.mostRecentCall.object).toEqual(TestClass);17    expect(originalFunctionWasCalled).toEqual(false);18    TestClass.someFunction('bar');19    expect(TestClass.someFunction.callCount).toEqual(2);20    expect(TestClass.someFunction.mostRecentCall.args).toEqual(['bar']);21  });22  it('should allow you to view args for a particular call', function() {23    var originalFunctionWasCalled = false;24    var TestClass = {25      someFunction: function() {26        originalFunctionWasCalled = true;27      }28    };29    this.spyOn(TestClass, 'someFunction');30    TestClass.someFunction('foo');31    TestClass.someFunction('bar');32    expect(TestClass.someFunction.calls[0].args).toEqual(['foo']);33    expect(TestClass.someFunction.calls[1].args).toEqual(['bar']);34    expect(TestClass.someFunction.mostRecentCall.args).toEqual(['bar']);35  });36  it('should be possible to call through to the original method, or return a specific result', function() {37    var originalFunctionWasCalled = false;38    var passedArgs;39    var passedObj;40    var TestClass = {41      someFunction: function() {42        originalFunctionWasCalled = true;43        passedArgs = arguments;44        passedObj = this;45        return "return value from original function";46      }47    };48    this.spyOn(TestClass, 'someFunction').andCallThrough();49    var result = TestClass.someFunction('arg1', 'arg2');50    expect(result).toEqual("return value from original function");51    expect(originalFunctionWasCalled).toEqual(true);52    expect(passedArgs).toEqual(['arg1', 'arg2']);53    expect(passedObj).toEqual(TestClass);54    expect(TestClass.someFunction.wasCalled).toEqual(true);55  });56  it('should be possible to return a specific value', function() {57    var originalFunctionWasCalled = false;58    var TestClass = {59      someFunction: function() {60        originalFunctionWasCalled = true;61        return "return value from original function";62      }63    };64    this.spyOn(TestClass, 'someFunction').andReturn("some value");65    originalFunctionWasCalled = false;66    var result = TestClass.someFunction('arg1', 'arg2');67    expect(result).toEqual("some value");68    expect(originalFunctionWasCalled).toEqual(false);69  });70  it('should be possible to throw a specific error', function() {71    var originalFunctionWasCalled = false;72    var TestClass = {73      someFunction: function() {74        originalFunctionWasCalled = true;75        return "return value from original function";76      }77    };78    this.spyOn(TestClass, 'someFunction').andThrow(new Error('fake error'));79    var exception;80    try {81      TestClass.someFunction('arg1', 'arg2');82    } catch (e) {83      exception = e;84    }85    expect(exception.message).toEqual('fake error');86    expect(originalFunctionWasCalled).toEqual(false);87  });88  it('should be possible to call a specified function', function() {89    var originalFunctionWasCalled = false;90    var fakeFunctionWasCalled = false;91    var passedArgs;92    var passedObj;93    var TestClass = {94      someFunction: function() {95        originalFunctionWasCalled = true;96        return "return value from original function";97      }98    };99    this.spyOn(TestClass, 'someFunction').andCallFake(function() {100      fakeFunctionWasCalled = true;101      passedArgs = arguments;102      passedObj = this;103      return "return value from fake function";104    });105    var result = TestClass.someFunction('arg1', 'arg2');106    expect(result).toEqual("return value from fake function");107    expect(originalFunctionWasCalled).toEqual(false);108    expect(fakeFunctionWasCalled).toEqual(true);109    expect(passedArgs).toEqual(['arg1', 'arg2']);110    expect(passedObj).toEqual(TestClass);111    expect(TestClass.someFunction.wasCalled).toEqual(true);112  });113  it('is torn down when this.removeAllSpies is called', function() {114    var originalFunctionWasCalled = false;115    var TestClass = {116      someFunction: function() {117        originalFunctionWasCalled = true;118      }119    };120    this.spyOn(TestClass, 'someFunction');121    TestClass.someFunction('foo');122    expect(originalFunctionWasCalled).toEqual(false);123    this.removeAllSpies();124    TestClass.someFunction('foo');125    expect(originalFunctionWasCalled).toEqual(true);126  });127  it('calls removeAllSpies during spec finish', function() {128    var test = new jasmine.Spec(new jasmine.Env(), {}, 'sample test');129    this.spyOn(test, 'removeAllSpies');130    test.finish();131    expect(test.removeAllSpies).wasCalled();132  });133  it('throws an exception when some method is spied on twice', function() {134    var TestClass = { someFunction: function() {135    } };136    this.spyOn(TestClass, 'someFunction');137    var exception;138    try {139      this.spyOn(TestClass, 'someFunction');140    } catch (e) {141      exception = e;142    }143    expect(exception).toBeDefined();144  });145  it('should be able to reset a spy', function() {146    var TestClass = { someFunction: function() {} };147    this.spyOn(TestClass, 'someFunction');148    expect(TestClass.someFunction).not.toHaveBeenCalled();149    TestClass.someFunction();150    expect(TestClass.someFunction).toHaveBeenCalled();151    TestClass.someFunction.reset();152    expect(TestClass.someFunction).not.toHaveBeenCalled();153    expect(TestClass.someFunction.callCount).toEqual(0);154  });155  describe("createSpyObj", function() {156    it("should create an object with a bunch of spy methods when you call jasmine.createSpyObj()", function() {157      var spyObj = jasmine.createSpyObj('BaseName', ['method1', 'method2']);158      expect(spyObj).toEqual({ method1: jasmine.any(Function), method2: jasmine.any(Function)});159      expect(spyObj.method1.identity).toEqual('BaseName.method1');160      expect(spyObj.method2.identity).toEqual('BaseName.method2');161    });162    it("should throw if you do not pass an array argument", function() {163      expect(function() {164        jasmine.createSpyObj('BaseName');165      }).toThrow('createSpyObj requires a non-empty array of method names to create spies for');166    });167    it("should throw if you pass an empty array argument", function() {168      expect(function() {169        jasmine.createSpyObj('BaseName');170      }).toThrow('createSpyObj requires a non-empty array of method names to create spies for');171    });172  });...test_event-target.js
Source:test_event-target.js  
...8            }9        });10    });11    it("takes a event listener", function(){12        var testClass = new TestClass();13        var callback = sinon.spy();14        testClass.addEventListener("touchstart", callback);15        expect(testClass._listeners["touchstart"][0]).to.deep.equal(callback);16        expect(Object.keys(testClass._listeners).length).to.equal(1);17        testClass.dispatchEvent(new Event("touchstart"));18        expect(callback.called).to.be.true;19    });20    it("takes several different types of event listener", function(){21        var testClass = new TestClass();22        var callback1 = sinon.spy(),23            callback2 = sinon.spy();24        testClass.addEventListener("touchstart", callback1);25        testClass.addEventListener("touchend", callback2);26        expect(testClass._listeners["touchstart"][0]).to.deep.equal(callback1);27        expect(testClass._listeners["touchend"][0]).to.deep.equal(callback2);28        expect(Object.keys(testClass._listeners).length).to.equal(2);29        testClass.dispatchEvent(new Event("touchstart"));30        testClass.dispatchEvent(new Event("touchend"))31        expect(callback1.called).to.be.true;32        expect(callback1.callCount).to.equal(1);33        expect(callback2.called).to.be.true;34        expect(callback2.callCount).to.equal(1);35    });36    it("takes multiple event listeners to one event type", function(){37        var testClass = new TestClass();38        var callback1 = sinon.spy(),39            callback2 = sinon.spy();40        testClass.addEventListener("touchstart", callback1);41        testClass.addEventListener("touchstart", callback2);42        expect(callback1.called).to.be.false;43        expect(callback2.called).to.be.false;44        testClass.dispatchEvent(new Event("touchstart"));45        expect(callback1.callCount).to.equal(1);46        expect(callback2.callCount).to.equal(1);47    });48    it("#on is synonym for #addEventListener", function(){49        var testClass = new TestClass();50        var callback = sinon.spy();51        testClass.on("touchstart", callback);52        expect(testClass._listeners["touchstart"][0]).to.deep.equal(callback);53        testClass.dispatchEvent(new Event("touchstart"));54        expect(callback.called).to.be.true;55        expect(callback.callCount).to.equal(1);56    });57    it("removes a event listener of itself", function(){58        var testClass = new TestClass();59        var callback = sinon.spy();60        testClass.addEventListener("touchstart", callback);61        testClass.dispatchEvent(new Event("touchstart"));62        expect(callback.callCount).to.equal(1);63        testClass.removeEventListener("touchstart", callback);64        testClass.dispatchEvent(new Event("touchstart"));65        expect(callback.callCount).to.equal(1);66    });67    it("removes event listener from a event which has multiple event listeners", function(){68        var testClass = new TestClass();69        var callback1 = sinon.spy(),70            callback2 = sinon.spy();71        testClass.addEventListener("touchstart", callback1);72        testClass.addEventListener("touchstart", callback2);73        expect(testClass._listeners["touchstart"][1]).to.deep.equal(callback1);74        expect(testClass._listeners["touchstart"][0]).to.deep.equal(callback2);75        testClass.removeEventListener("touchstart", callback2);76        expect(testClass._listeners["touchstart"][0]).to.deep.equal(callback1);77        testClass.dispatchEvent(new Event("touchstart"));78        expect(callback1.callCount).to.equal(1);79        expect(callback2.called).to.be.false;80    });81    it("removes event listener from class which has multiple event listeners on multiple events", function(){82        var testClass = new TestClass();83        var callback1 = sinon.spy(),84            callback2 = sinon.spy();85        testClass.addEventListener("touchstart", callback1);86        testClass.addEventListener("touchend", callback2);87        testClass.dispatchEvent(new Event("touchend"));88        expect(callback1.callCount).to.equal(0);89        expect(callback2.callCount).to.equal(1);90        testClass.removeEventListener("touchend", callback2);91        testClass.dispatchEvent(new Event("touchend"));92        expect(callback2.callCount).to.equal(1);93        expect(testClass._listeners["touchend"].length).to.be.zero;94        expect(Object.keys(testClass._listeners["touchstart"]).length).to.equal(1);95    });96    it("removes all event listeners from all events", function(){97        var sprite = new Sprite();98        expect(Object.keys(sprite._listeners).length).to.be.above(2);99        sprite.clearEventListener();100        expect(Object.keys(sprite._listeners).length).to.be.zero;101    });102    it("removes all event listeners related to one event", function(){103        var testClass = new TestClass();104        var callback1 = sinon.spy(),105            callback2 = sinon.spy(),106            callback3 = sinon.spy();107        testClass.addEventListener("touchstart", callback1);108        testClass.addEventListener("touchstart", callback2);109        testClass.addEventListener("touchend", callback3);110        expect(testClass._listeners["touchstart"].length).to.equal(2);111        expect(testClass._listeners["touchend"].length).to.equal(1);112        testClass.clearEventListener("touchstart");113        expect(testClass._listeners["touchstart"]).to.be.undefined;114        expect(testClass._listeners["touchend"].length).to.equal(1);115    });116    it("dispatches enchant.Event", function(){117        var testClass = new TestClass();118        var callback1 = sinon.spy(),119            callback2 = sinon.spy(),120            callback3 = sinon.spy();121        testClass.addEventListener("touchstart", callback1);122        testClass.addEventListener("touchmove", callback2);123        testClass.addEventListener("touchend", callback3);124        testClass.dispatchEvent(new Event("touchstart"));125        expect(callback1.callCount).to.equal(1);126        expect(callback2.callCount).to.be.zero;127        expect(callback3.callCount).to.be.zero;128        testClass.dispatchEvent(new Event("touchmove"));129        expect(callback1.callCount).to.equal(1);130        expect(callback2.callCount).to.equal(1);131        expect(callback3.callCount).to.be.zero;...test_class.js
Source:test_class.js  
...5    it("is a class", function(){6        var TestClass = enchant.Class(Object, {});7        expect(TestClass.prototype.constructor).to.exist;8        expect(TestClass.prototype.initialize).to.exist;9        var tc = new TestClass();10        expect(tc).to.be.an.instanceOf(TestClass);11    });12    describe("#create", function(){13        it("throws Error when arguments are invalid", function(){14            expect(function(){enchant.Class.create();}).to.throw(/definition is undefined/);15            expect(function(){enchant.Class.create(null, {});}).to.throw(/superclass is undefined/);16        });17        it("creates independent class", function(){18            var TestClass = enchant.Class.create({19                foo: function(){20                    return 'foo';21                }22            });23            expect(TestClass.prototype.constructor).to.exist;24            expect(TestClass.prototype.initialize).to.exist;25            expect(TestClass.prototype.foo).to.exist;26            var tc = new TestClass();27            expect(tc.foo()).to.equal('foo');28        });29        it("creates a class inheritting existing Class", function(){30            var TestClass = enchant.Class.create(Sprite);31            expect(TestClass.prototype.initialize).to.deep.equal(Sprite.prototype.initialize);32            expect(TestClass.prototype.cvsRender, "inherit from enchant.Sprite").to.exist;33            expect(TestClass.prototype.within, "inherit from enchant.Entity").to.exist;34            var tc = new TestClass(10, 10);35            expect(tc.height).to.equal(10);36            expect(tc.width).to.equal(10);37        });38        it("creates a class inheritting existing Class and overwrite constructor", function(){39            var TestClass = enchant.Class.create(Sprite, {40                initialize: function(width, height){41                    enchant.Sprite.call(this);42                    this.width = 2 * width43                    this.height = 2 * height;44                }45            });46            expect(TestClass.prototype.initialize).not.to.deep.equal(Sprite.prototype.initialize);47            expect(TestClass.prototype.cvsRender, "inherit from enchant.Sprite").to.exist;48            expect(TestClass.prototype.within, "inherit from enchant.Entity").to.exist;49            var tc = new TestClass(10, 10);50            expect(tc.height).to.equal(20);51            expect(tc.width).to.equal(20);52        });53    });54    describe("#getInheritanceTree", function(){55        it("returns inheritance tree array", function(){56            var inheritanceTree = enchant.Class.getInheritanceTree(enchant.Sprite);57            expect(inheritanceTree.length).to.equal(4);58         });59    });...Using AI Code Generation
1describe('TestClass', function () {2    it('should call the callback', function () {3        var callback = sinon.spy();4        var testClass = new TestClass();5        testClass.testMethod(callback);6        expect(callback.called).to.be.true;7    });8});9describe('TestClass', function () {10    it('should call the callback', function () {11        var callback = sinon.spy();12        var testClass = new TestClass();13        testClass.testMethod(callback);14        expect(callback.called).to.be.true;15    });16});Using AI Code Generation
1var assert = require('assert');2var sinon = require('sinon');3var TestClass = require('./TestClass');4describe('TestClass', function() {5  describe('#method', function() {6    it('should call callback', function() {7      var callback = sinon.spy();8      var testClass = new TestClass();9      testClass.method(callback);10      assert(callback.called);11    });12  });13});14var TestClass = function() {};15TestClass.prototype.method = function(callback) {16  callback();17};18module.exports = TestClass;19var assert = require('assert');20var sinon = require('sinon');21var TestClass = require('./TestClass');22describe('TestClass', function() {23  describe('#method', function() {24    it('should call callback', function() {25      var callback = sinon.spy();26      var testClass = new TestClass();27      testClass.method(callback);28      assert(callback.called);29    });30  });31});32var TestClass = function() {};33TestClass.prototype.method = function(callback) {34  callback();35};36module.exports = TestClass;37var assert = require('assert');38var sinon = require('sinon');39var TestClass = require('./TestClass');40describe('TestClass', function() {41  describe('#method', function() {42    it('should call callback', function() {43      var callback = sinon.spy();44      var testClass = new TestClass();45      testClass.method(callback);46      assert(callback.called);47    });48  });49});50var TestClass = function() {};51TestClass.prototype.method = function(callback) {52  callback();53};54module.exports = TestClass;55var assert = require('assert');56var sinon = require('sinon');57var TestClass = require('./TestClass');58describe('TestClass', function() {59  describe('#method', function() {60    it('should call callback', function() {61      var callback = sinon.spy();62      var testClass = new TestClass();63      testClass.method(callback);64      assert(callback.called);65    });66  });67});Using AI Code Generation
1var sinon = require('sinon');2var assert = require('assert');3var TestClass = require('../testClass.js');4var testClass = new TestClass();5var spy = sinon.spy(testClass, "testMethod");6testClass.testMethod(1, 2);7assert(spy.calledOnce);8assert(spy.calledWith(1, 2));9assert(spy.returned(3));10var sinon = require('sinon');11var assert = require('assert');12var TestClass = require('../testClass.js');13var testClass = new TestClass();14var stub = sinon.stub(testClass, "testMethod");15stub.returns(42);16var result = testClass.testMethod(1, 2);17assert(stub.calledOnce);18assert(stub.calledWith(1, 2));19assert(stub.returned(42));20assert.equal(result, 42);21var sinon = require('sinon');22var assert = require('assert');23var TestClass = require('../testClass.js');24var testClass = new TestClass();25var stub = sinon.stub(testClass, "testMethod");26stub.withArgs(1, 2).returns(42);27stub.withArgs(3, 4).returns(43);28var result1 = testClass.testMethod(1, 2);29var result2 = testClass.testMethod(3, 4);30assert(stub.calledTwice);31assert(stub.calledWith(1, 2));32assert(stub.calledWith(3, 4));33assert(stub.returned(42));34assert(stub.returned(43));35assert.equal(result1, 42);36assert.equal(result2, 43);37var sinon = require('sinon');38var assert = require('assert');39var TestClass = require('../testClass.js');40var testClass = new TestClass();41var stub = sinon.stub(testClass, "testMethod");42stub.withArgs(1, 2).throws("Error");43stub.withArgs(3, 4).returns(43);44var result1 = testClass.testMethod(1, 2);45var result2 = testClass.testMethod(3, 4);46assert(stub.calledTwice);47assert(stub.calledWith(1, 2));48assert(stub.calledWith(3, 4));Using AI Code Generation
1test('test', function() {2    var testClass = new TestClass();3    var stub = sinon.stub(testClass, 'method', function() {4        return 'stubbed';5    });6    assert.equal(testClass.method(), 'stubbed');7    stub.restore();8});9test('test', function() {10    var testClass = new TestClass();11    var stub = sinon.stub(testClass, 'method', function() {12        return 'stubbed';13    });14    assert.equal(testClass.method(), 'stubbed');15    stub.restore();16});17test('test', function() {18    var testClass = new TestClass();19    var stub = sinon.stub(testClass, 'method', function() {20        return 'stubbed';21    });22    assert.equal(testClass.method(), 'stubbed');23    stub.restore();24});25test('test', function() {26    var testClass = new TestClass();27    var stub = sinon.stub(testClass, 'method', function() {28        return 'stubbed';29    });30    assert.equal(testClass.method(), 'stubbed');31    stub.restore();32});33test('test', function() {34    var testClass = new TestClass();35    var stub = sinon.stub(testClass, 'method', function() {36        return 'stubbed';37    });38    assert.equal(testClass.method(), 'stubbed');39    stub.restore();40});41test('test', function() {42    var testClass = new TestClass();43    var stub = sinon.stub(testClass, 'method', function() {44        return 'stubbed';45    });46    assert.equal(testClass.method(), 'stubbed');47    stub.restore();48});49test('test', function() {50    var testClass = new TestClass();51    var stub = sinon.stub(testClass, 'method', function() {52        return 'stubbed';53    });54    assert.equal(testClass.method(), 'stubbed');55    stub.restore();56});57test('Using AI Code Generation
1var testClass = require('../testClass');2var sinon = require('sinon');3var assert = require('assert');4describe('Test', function() {5  describe('#testMethod()', function() {6    it('should call the callback', function() {7      var stub = sinon.stub(testClass, 'testMethod');8      var callback = sinon.spy();9      testClass.testMethod(callback);10      assert(stub.calledOnce);11      assert(callback.calledOnce);12    });13  });14});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!!
