How to use createSpy method in Jest

Best JavaScript code snippet using jest

q_spec.js

Source:q_spec.js Github

copy

Full Screen

...21    });22    it('can resolve a promise', function (done) {23        var defferred = $q.defer();24        var promise = defferred.promise;25        var promiseSpy = jasmine.createSpy();26        promise.then(promiseSpy);27        defferred.resolve('a-ok');28        setTimeout(function () {29           expect(promiseSpy).toHaveBeenCalledWith('a-ok');30           done();31        },1);32    });33    it('works when resolved before promise listener', function (done) {34        var d = $q.defer();35        d.resolve(42);36        var promiseSpy = jasmine.createSpy();37        d.promise.then(promiseSpy);38        setTimeout(function () {39            expect(promiseSpy).toHaveBeenCalledWith(42);40            done();41        },0);42    });43    it('does not resolve promise immediately', function () {44        var d = $q.defer();45        var promiseSpy = jasmine.createSpy();46        d.promise.then(promiseSpy);47        d.resolve(42);48        expect(promiseSpy).not.toHaveBeenCalled();49    });50    it('resolves promise at next digest', function () {51       var d = $q.defer();52       var promiseSpy = jasmine.createSpy();53       d.promise.then(promiseSpy);54       d.resolve(42);55       $rootScope.$apply();56       expect(promiseSpy).toHaveBeenCalledWith(42);57    });58    it('may only be resolved once', function () {59       var d = $q.defer();60       var promiseSpy = jasmine.createSpy();61       d.promise.then(promiseSpy);62       d.resolve(42);63       d.resolve(43);64       $rootScope.$apply();65       expect(promiseSpy.calls.count()).toEqual(1);66       expect(promiseSpy).toHaveBeenCalledWith(42);67    });68    it('may only ever be resolved once',function () {69        var d = $q.defer();70        var promiseSpy = jasmine.createSpy();71        d.promise.then(promiseSpy);72        d.resolve(42);73        $rootScope.$apply();74        expect(promiseSpy).toHaveBeenCalledWith(42);75        d.resolve(43);76        $rootScope.$apply();77        expect(promiseSpy.calls.count()).toEqual(1);78    });79    it('resolves a listener added after resolution', function () {80       var d = $q.defer();81       d.resolve(42);82       $rootScope.$apply();83       var promiseSpy = jasmine.createSpy();84       d.promise.then(promiseSpy);85       $rootScope.$apply();86       expect(promiseSpy).toHaveBeenCalledWith(42);87    });88    it('may have multiple callbacks', function () {89       var d = $q.defer();90       var firstPromise = jasmine.createSpy();91       var secondPromise = jasmine.createSpy();92       d.promise.then(firstPromise);93       d.promise.then(secondPromise);94       d.resolve(42);95       $rootScope.$apply();96       expect(firstPromise).toHaveBeenCalledWith(42);97       expect(secondPromise).toHaveBeenCalledWith(42);98    });99    it('invokes each callback once', function () {100       var d = $q.defer();101       var firstSpy = jasmine.createSpy();102       var secondSpy = jasmine.createSpy();103       d.promise.then(firstSpy);104       d.resolve(42);105       $rootScope.$apply();106       expect(firstSpy.calls.count()).toBe(1);107       expect(secondSpy.calls.count()).toBe(0);108       d.promise.then(secondSpy);109       $rootScope.$apply();110        expect(firstSpy.calls.count()).toBe(1);111        expect(secondSpy.calls.count()).toBe(1);112    });113    it('can reject a deferred', function () {114        var d = $q.defer();115        var fullfillSpy = jasmine.createSpy();116        var rejectSpy = jasmine.createSpy();117        d.promise.then(fullfillSpy, rejectSpy);118        d.reject('fail');119        $rootScope.$apply();120        expect(fullfillSpy).not.toHaveBeenCalled();121        expect(rejectSpy).toHaveBeenCalledWith('fail');122    });123    it('can reject just once', function () {124        var d = $q.defer();125        var rejectSpy = jasmine.createSpy();126        d.promise.then(null, rejectSpy);127        d.reject('fail');128        $rootScope.$apply();129        expect(rejectSpy.calls.count()).toBe(1);130        d.reject('fail again');131        $rootScope.$apply();132        expect(rejectSpy.calls.count()).toBe(1);133    });134    it('cannot fulfill a promise once rejected', function () {135       var d = $q.defer();136       var fulfillSpy = jasmine.createSpy();137       var rejectSpy = jasmine.createSpy();138       d.promise.then(fulfillSpy, rejectSpy);139       d.reject('fail');140       $rootScope.$apply();141       d.resolve('success');142       $rootScope.$apply();143       expect(fulfillSpy).not.toHaveBeenCalled();144    });145    it('does not require a failure handler each time', function () {146        var d = $q.defer();147        var fulfillSpy = jasmine.createSpy();148        var rejectSpy = jasmine.createSpy();149        d.promise.then(fulfillSpy);150        d.promise.then(null,rejectSpy);151        d.reject('fail');152        $rootScope.$apply();153        expect(rejectSpy).toHaveBeenCalledWith('fail');154    });155    it('does not require a success handler each time', function () {156        var d = $q.defer();157        var fulfillSpy = jasmine.createSpy();158        var rejectSpy = jasmine.createSpy();159        d.promise.then(fulfillSpy);160        d.promise.then(null,rejectSpy);161        d.resolve('ok');162        $rootScope.$apply();163        expect(fulfillSpy).toHaveBeenCalledWith('ok');164    });165    it('can register rejection handler with catch', function () {166        var d = $q.defer();167        var rejectSpy = jasmine.createSpy();168        d.promise.catch(rejectSpy);169        d.reject('fail');170        $rootScope.$apply();171        expect(rejectSpy).toHaveBeenCalled();172    });173    it('invokes a finally handler when fulfilled', function () {174       var d = $q.defer();175       var finallySpy = jasmine.createSpy();176       d.promise.finally(finallySpy);177       d.resolve(42);178       $rootScope.$apply();179       expect(finallySpy).toHaveBeenCalled();180    });181    it('invokes a finally handler when rejected', function () {182        var d = $q.defer();183        var finallySpy = jasmine.createSpy();184        d.promise.finally(finallySpy);185        d.reject('fail');186        $rootScope.$apply();187        expect(finallySpy).toHaveBeenCalledWith();188    });189    it('allows chaining handlers', function () {190       var d = $q.defer();191       var fulfilledSpy = jasmine.createSpy();192       d.promise.then(function (result) {193           return result + 1;194       }).then(function (result) {195           return result * 2;196       }).then(fulfilledSpy);197       d.resolve(20);198       $rootScope.$apply();199       expect(fulfilledSpy).toHaveBeenCalledWith(42);200    });201    it('does not modify original resolution in chains', function () {202        var d = $q.defer();203        var fulfilledSpy = jasmine.createSpy();204        d.promise.then(function (result) {205            return result + 1;206        }).then(function (result) {207            return result * 2;208        });209        d.promise.then(fulfilledSpy);210        d.resolve(20);211        $rootScope.$apply();212        expect(fulfilledSpy).toHaveBeenCalledWith(20);213    });214    it('catches rejection on chained handler', function () {215       var d = $q.defer();216       var rejectedSpy = jasmine.createSpy();217       d.promise.then(_.noop).catch(rejectedSpy);218       d.reject('fail');219       $rootScope.$apply();220       expect(rejectedSpy).toHaveBeenCalledWith('fail');221    });222    it('fulfills on chained handler', function () {223        var d = $q.defer();224        var fulfilledSpy = jasmine.createSpy();225        d.promise.catch(_.noop).then(fulfilledSpy);226        d.resolve(42);227        $rootScope.$apply();228        expect(fulfilledSpy).toHaveBeenCalledWith(42);229    });230    it('treats catch return value as resolution', function () {231        var d = $q.defer();232        var fulfillSpy = jasmine.createSpy();233        d.promise.catch(function (value) {234            return 42;235        }).then(fulfillSpy);236        d.reject('fail');237        $rootScope.$apply();238        expect(fulfillSpy).toHaveBeenCalledWith(42);239    });240    it('rejects chained promise when handler throws', function () {241        var d = $q.defer();242        var rejectSpy = jasmine.createSpy();243        d.promise.then(function () {244            throw 'fail';245        }).catch(rejectSpy);246        d.resolve(42);247        $rootScope.$apply();248        expect(rejectSpy).toHaveBeenCalledWith('fail');249    });250    it('does not reject current promise when handler throws', function () {251       var d = $q.defer();252       var rejectSpy = jasmine.createSpy();253       d.promise.then(function () {254           throw 'fail';255       });256       d.promise.catch(rejectSpy);257       d.resolve(42);258       $rootScope.$apply();259       expect(rejectSpy).not.toHaveBeenCalled();260    });261    it('waits on promise returned from handler', function () {262        var d = $q.defer();263        var fulfilledSpy = jasmine.createSpy();264        d.promise.then(function (v) {265            var d2 = $q.defer();266            d2.resolve(v+1);267            return d2.promise;268        }).then(function (v) {269            return v*2;270        }).then(fulfilledSpy);271        d.resolve(20);272        $rootScope.$apply();273        expect(fulfilledSpy).toHaveBeenCalledWith(42);274    });275    it('waits on promise given to resolve', function () {276        var d = $q.defer();277        var d2 = $q.defer();278        var fulfilledSpy = jasmine.createSpy();279        d.promise.then(fulfilledSpy);280        d2.resolve(42);281        d.resolve(d2.promise);282        $rootScope.$apply();283        expect(fulfilledSpy).toHaveBeenCalledWith(42);284    });285    it('rejects when promise returned from handler rejects', function () {286       var d = $q.defer();287       var rejectSpy = jasmine.createSpy();288       d.promise.then(function () {289           var d2 = $q.defer();290           d2.reject('fail');291           return d2.promise;292       }).catch(rejectSpy);293       d.resolve('ok');294       $rootScope.$apply();295       expect(rejectSpy).toHaveBeenCalledWith('fail');296    });297    it('allows chaining handlers on finally, with original value', function () {298        var d = $q.defer();299        var fulfilledSpy = jasmine.createSpy();300        d.promise.then(function (result) {301            return result +1;302        }).finally(function (result) {303            return result*2;304        }).then(fulfilledSpy);305        d.resolve(20);306        $rootScope.$apply();307        expect(fulfilledSpy).toHaveBeenCalledWith(21);308    });309    it('allows chaining handlers on finally, with original rejection', function () {310        var d = $q.defer();311        var rejectSpy = jasmine.createSpy();312        d.promise.then(function (result) {313            throw 'fail';314        }).finally(function () {315        }).catch(rejectSpy);316        d.resolve(20);317        $rootScope.$apply();318        expect(rejectSpy).toHaveBeenCalledWith('fail');319    });320    it('resolves to orig value when nested promise resolves', function () {321       var d = $q.defer();322       var fulfilledSpy = jasmine.createSpy();323       var resolveNested;324       d.promise.then(function (result) {325           return result + 1;326       }).finally(function (result) {327            var d2 = $q.defer();328            resolveNested = function () {329                d2.resolve('abc');330            };331            return d2.promise;332       }).then(fulfilledSpy);333       d.resolve(20);334       $rootScope.$apply();335       expect(fulfilledSpy).not.toHaveBeenCalled();336       resolveNested();337       $rootScope.$apply();338       expect(fulfilledSpy).toHaveBeenCalledWith(21);339    });340    it('rejects to orig value when nested promise resolves', function () {341       var d = $q.defer();342       var rejectSpy = jasmine.createSpy();343       var resolveNested;344       d.promise.then(function (result) {345           throw 'fail';346       }).finally(function (result) {347           var d2 = $q.defer();348           resolveNested = function () {349               d2.resolve('abc');350           };351           return d2.promise;352       }).catch(rejectSpy);353       d.resolve(20);354       $rootScope.$apply();355       expect(rejectSpy).not.toHaveBeenCalled();356       resolveNested();357       $rootScope.$apply();358       expect(rejectSpy).toHaveBeenCalledWith('fail');359    });360    it('rejects when nested promise rejects in finally', function () {361       var d = $q.defer();362       var fulfilledSpy = jasmine.createSpy();363       var rejectedSpy = jasmine.createSpy();364       var rejectNested;365       d.promise.then(function (result) {366           return result + 1;367       }).finally(function (result) {368           var d2 = $q.defer();369           rejectNested = function () {370               d2.reject('fail');371           };372           return d2.promise;373       }).then(fulfilledSpy, rejectedSpy);374       d.resolve(20);375       $rootScope.$apply();376       expect(fulfilledSpy).not.toHaveBeenCalled();377       rejectNested();378       $rootScope.$apply();379       expect(fulfilledSpy).not.toHaveBeenCalled();380       expect(rejectedSpy).toHaveBeenCalledWith('fail');381    });382    it('can report progress', function () {383       var d = $q.defer();384       var progressSpy = jasmine.createSpy();385       d.promise.then(null, null, progressSpy);386       d.notify('working...');387       $rootScope.$apply();388       expect(progressSpy).toHaveBeenCalledWith('working...');389    });390    it('can report progress many times', function () {391        var d = $q.defer();392        var progressSpy = jasmine.createSpy();393        d.promise.then(null, null, progressSpy);394        d.notify('40%');395        $rootScope.$apply();396        d.notify('60%');397        d.notify('80%');398        $rootScope.$apply();399        expect(progressSpy.calls.count()).toBe(3);400    });401    it('does not notify progress after being resolved', function () {402       var d = $q.defer();403       var progressSpy = jasmine.createSpy();404       d.promise.then(null, null, progressSpy);405       d.resolve('ok');406       d.notify('working...');407       $rootScope.$apply();408       expect(progressSpy).not.toHaveBeenCalled();409    });410    it('does not notify progress after being rejected', function () {411       var d = $q.defer();412       var progressSpy = jasmine.createSpy();413       d.promise.then(null, null, progressSpy);414       d.reject('fail');415       d.notify('working...');416       $rootScope.$apply();417       expect(progressSpy).not.toHaveBeenCalled();418    });419    it('can notify progress through chain', function () {420       var d = $q.defer();421       var progressSpy = jasmine.createSpy();422       d.promise.then(_.noop).catch(_.noop).then(null, null, progressSpy);423       d.notify('working...');424       $rootScope.$apply();425       expect(progressSpy).toHaveBeenCalledWith('working...');426    });427    it('transforms progress through handlers', function () {428       var d = $q.defer();429       var progressSpy = jasmine.createSpy();430       d.promise.then(_.noop).then(null, null, function (progress) {431           return '***' + progress + '***';432       }).catch(_.noop).then(null, null, progressSpy);433       d.notify('working...');434       $rootScope.$apply();435       expect(progressSpy).toHaveBeenCalledWith('***working...***');436    });437    it('recovers from progressback exceptions', function () {438       var d = $q.defer();439       var progressSpy = jasmine.createSpy();440       var fulfilledSpy = jasmine.createSpy();441       d.promise.then(null, null, function (progress) {442           throw 'fail';443       });444       d.promise.then(fulfilledSpy, null, progressSpy);445       d.notify('working...');446       d.resolve('ok');447       $rootScope.$apply();448       expect(progressSpy).toHaveBeenCalledWith('working...');449       expect(fulfilledSpy).toHaveBeenCalledWith('ok');450    });451    it('can notify progress through promise returned from handler', function () {452       var d = $q.defer();453       var progressSpy = jasmine.createSpy();454       d.promise.then(null, null, progressSpy);455       var d2 = $q.defer();456       d.resolve(d2.promise);457       d2.notify('working...');458       $rootScope.$apply();459       expect(progressSpy).toHaveBeenCalledWith('working...');460    });461    it('allows attaching progressback in finally', function () {462        var d = $q.defer();463        var progressSpy = jasmine.createSpy();464        d.promise.finally(null, progressSpy);465        d.notify('working...');466        $rootScope.$apply();467        expect(progressSpy).toHaveBeenCalledWith('working...');468    });469    it('can make an immediately rejected promise', function () {470       var fulfilledSpy = jasmine.createSpy();471       var rejectSpy = jasmine.createSpy();472       var promise = $q.reject('fail');473       promise.then(fulfilledSpy, rejectSpy);474       $rootScope.$apply();475       expect(fulfilledSpy).not.toHaveBeenCalled();476       expect(rejectSpy).toHaveBeenCalledWith('fail');477    });478    it('can make an immediately resolved promise', function () {479       var fulfilledSpy = jasmine.createSpy();480       var rejectedSpy = jasmine.createSpy();481       var promise = $q.when('ok');482       promise.then(fulfilledSpy, rejectedSpy);483       $rootScope.$apply();484       expect(fulfilledSpy).toHaveBeenCalledWith('ok');485       expect(rejectedSpy).not.toHaveBeenCalled();486    });487    it('can wrap a foreign promise', function () {488       var fulfilledSpy = jasmine.createSpy();489       var rejectedSpy = jasmine.createSpy();490       var promise = $q.when({491           then: function (handler) {492               $rootScope.$evalAsync(function () {493                   handler('ok');494               });495           }496       });497       promise.then(fulfilledSpy, rejectedSpy);498       $rootScope.$apply();499       expect(fulfilledSpy).toHaveBeenCalledWith('ok');500       expect(rejectedSpy).not.toHaveBeenCalled();501    });502    it('takes callbacks directly when wrapping', function () {503       var fulfilledSpy = jasmine.createSpy();504       var rejectedSpy = jasmine.createSpy();505       var progressSpy = jasmine.createSpy();506       var wrapped = $q.defer();507       $q.when(508           wrapped.promise,509           fulfilledSpy,510           rejectedSpy,511           progressSpy512       );513       wrapped.notify('working...');514       wrapped.resolve('ok');515       $rootScope.$apply();516       expect(fulfilledSpy).toHaveBeenCalledWith('ok');517       expect(rejectedSpy).not.toHaveBeenCalled();518       expect(progressSpy).toHaveBeenCalledWith('working...');519    });520    it('makes an immediately resolved promise with resolve', function () {521       var fulfilledSpy = jasmine.createSpy();522       var rejectedSpy = jasmine.createSpy();523       var promise = $q.resolve('ok');524       promise.then(fulfilledSpy, rejectedSpy);525       $rootScope.$apply();526       expect(fulfilledSpy).toHaveBeenCalledWith('ok');527       expect(rejectedSpy).not.toHaveBeenCalled();528    });529    describe('all', function () {530        it('can resolve an array of promises to array of results', function () {531           var promise = $q.all([$q.when(1), $q.when(2), $q.when(3)]);532           var fulfilledSpy = jasmine.createSpy();533           promise.then(fulfilledSpy);534           $rootScope.$apply();535           expect(fulfilledSpy).toHaveBeenCalledWith([1,2,3]);536        });537        it('can resolve an object of promises to an object of results', function () {538            var promise = $q.all({a: $q.when(1), b: $q.when(2)});539            var fulfilledSpy = jasmine.createSpy();540            promise.then(fulfilledSpy);541            $rootScope.$apply();542            expect(fulfilledSpy).toHaveBeenCalledWith({a: 1, b: 2});543        });544        it('resolves an empty array of  promises immediately', function () {545           var promise = $q.all([]);546           var fulfilledSpy = jasmine.createSpy();547           promise.then(fulfilledSpy);548           $rootScope.$apply();549           expect(fulfilledSpy).toHaveBeenCalledWith([]);550        });551        it('resolves an empty object of promises immediately', function () {552            var promise = $q.all({});553            var fulfilledSpy = jasmine.createSpy();554            promise.then(fulfilledSpy);555            $rootScope.$apply();556            expect(fulfilledSpy).toHaveBeenCalledWith({});557        });558        it('rejects when any of the promises rejects', function () {559           // var promise = $q.all([$q.when(1), $q.when(2), $q.reject('fail')]);560           // var fulfilledSpy = jasmine.createSpy();561           // var rejectedSpy = jasmine.createSpy();562           // promise.then(fulfilledSpy, rejectedSpy);563           // $rootScope.$apply();564           // expect(fulfilledSpy).not.toHaveBeenCalled();565           // expect(rejectedSpy).toHaveBeenCalledWith('fail');566        });567        it('wraps non-promise in the input colletion', function () {568           var promise = $q.all([$q.when(1),2,3]);569           var fulfilledSpy = jasmine.createSpy();570           promise.then(fulfilledSpy);571           $rootScope.$apply();572           expect(fulfilledSpy).toHaveBeenCalledWith([1,2,3]);573        });574    });575    describe('ES2015 style', function () {576        it('is a function', function () {577            expect($q instanceof Function).toBe(true);578        });579        it('expects a function as an argument', function () {580            expect($q).toThrow();581            $q(_.noop);582        });583        it('returns a promises', function () {584            expect($q(_.noop)).toBeDefined();585            expect($q(_.noop).then).toBeDefined();586        });587        it('calls function with a resolve function', function () {588           var fulfilledSpy = jasmine.createSpy();589           $q(function (resolve) {590               resolve('ok');591           }).then(fulfilledSpy);592           $rootScope.$apply();593           expect(fulfilledSpy).toHaveBeenCalledWith('ok');594        });595        it('calls function with a reject funtion', function () {596           var fulfiledSpy = jasmine.createSpy();597           var rejectedSpy = jasmine.createSpy();598           $q(function (resolve, reject) {599               reject('fail');600           }).then(fulfiledSpy, rejectedSpy);601           $rootScope.$apply();602           expect(fulfiledSpy).not.toHaveBeenCalled();603           expect(rejectedSpy).toHaveBeenCalledWith('fail');604        });605    });606    describe('$$q', function () {607        beforeEach(function () {608            jasmine.clock().install();609        });610        afterEach(function () {611            jasmine.clock().uninstall();612        });613        it('uses deferreds that do not resolve at digest', function () {614           var d = $$q.defer();615           var fulfilledSpy = jasmine.createSpy();616           d.promise.then(fulfilledSpy);617           d.resolve('ok');618           $rootScope.$apply();619           expect(fulfilledSpy).not.toHaveBeenCalled();620        });621        it('uses deferreds that resolve later', function () {622           var d = $$q.defer();623           var fulfilledSpy = jasmine.createSpy();624           d.promise.then(fulfilledSpy);625           d.resolve('ok');626           jasmine.clock().tick(1);627           expect(fulfilledSpy).toHaveBeenCalledWith('ok');628        });629        it('does not invoke digest', function () {630            var d = $$q.defer();631            d.promise.then(_.noop);632            d.resolve('ok');633            var watchSpy = jasmine.createSpy();634            $rootScope.$watch(watchSpy);635            jasmine.clock().tick(1);636            expect(watchSpy).not.toHaveBeenCalled();637        });638    });...

Full Screen

Full Screen

simple_fakes.js

Source:simple_fakes.js Github

copy

Full Screen

...40    this.variants = [];41    /** @type {shaka.extern.AbrManager.SwitchCallback} */42    this.switchCallback = null;43    /** @type {!jasmine.Spy} */44    this.init = jasmine.createSpy('init').and.callFake((switchCallback) => {45      this.switchCallback = switchCallback;46    });47    /** @type {!jasmine.Spy} */48    this.stop = jasmine.createSpy('stop');49    /** @type {!jasmine.Spy} */50    this.enable = jasmine.createSpy('enable');51    /** @type {!jasmine.Spy} */52    this.disable = jasmine.createSpy('disable');53    /** @type {!jasmine.Spy} */54    this.segmentDownloaded = jasmine.createSpy('segmentDownloaded');55    /** @type {!jasmine.Spy} */56    this.getBandwidthEstimate = jasmine.createSpy('getBandwidthEstimate');57    /** @type {!jasmine.Spy} */58    this.chooseVariant = jasmine.createSpy('chooseVariant').and.callFake(() => {59      return this.variants[this.chooseIndex];60    });61    /** @type {!jasmine.Spy} */62    this.setVariants = jasmine.createSpy('setVariants').and.callFake((arg) => {63      this.variants = arg;64    });65    /** @type {!jasmine.Spy} */66    this.playbackRateChanged = jasmine.createSpy('playbackRateChanged');67    /** @type {!jasmine.Spy} */68    this.configure = jasmine.createSpy('configure');69  }70};71/** @extends {shaka.media.StreamingEngine} */72shaka.test.FakeStreamingEngine = class {73  constructor() {74    let activeVariant = null;75    let activeText = null;76    /** @type {!jasmine.Spy} */77    this.destroy = jasmine.createSpy('destroy').and.callFake(() => {78      activeVariant = null;79      activeText = null;80      return Promise.resolve();81    });82    /** @type {!jasmine.Spy} */83    this.configure = jasmine.createSpy('configure');84    /** @type {!jasmine.Spy} */85    this.seeked = jasmine.createSpy('seeked');86    /** @type {!jasmine.Spy} */87    this.getCurrentVariant =88        jasmine.createSpy('getCurrentVariant').and.callFake(89            () => activeVariant);90    /** @type {!jasmine.Spy} */91    this.getCurrentTextStream =92        jasmine.createSpy('getCurrentTextStream').and.callFake(93            () => activeText);94    /** @type {!jasmine.Spy} */95    this.unloadTextStream =96        jasmine.createSpy('unloadTextStream').and.callFake(() => {97          activeText = null;98        });99    /** @type {!jasmine.Spy} */100    this.start = jasmine.createSpy('start');101    /** @type {!jasmine.Spy} */102    this.switchVariant =103        jasmine.createSpy('switchVariant').and.callFake((variant) => {104          activeVariant = variant;105        });106    /** @type {!jasmine.Spy} */107    this.switchTextStream =108        jasmine.createSpy('switchTextStream').and.callFake((textStream) => {109          activeText = textStream;110        });111  }112};113/** @extends {shaka.extern.ManifestParser} */114shaka.test.FakeManifestParser = class {115  /** @param {shaka.extern.Manifest} manifest */116  constructor(manifest) {117    /** @type {shaka.extern.ManifestParser.PlayerInterface} */118    this.playerInterface = null;119    /** @type {!jasmine.Spy} */120    this.start = jasmine.createSpy('start').and.callFake(121        async (manifestUri, playerInterface) => {122          this.playerInterface = playerInterface;123          await Promise.resolve();124          return manifest;125        });126    /** @type {!jasmine.Spy} */127    this.stop = jasmine.createSpy('stop').and.returnValue(Promise.resolve());128    /** @type {!jasmine.Spy} */129    this.configure = jasmine.createSpy('configure');130    /** @type {!jasmine.Spy} */131    this.update = jasmine.createSpy('update');132    /** @type {!jasmine.Spy} */133    this.onExpirationUpdated = jasmine.createSpy('onExpirationUpdated');134  }135};136/** @extends {HTMLVideoElement} */137shaka.test.FakeVideo = class {138  /** @param {number=} currentTime */139  constructor(currentTime) {140    /** @const {!Object.<string, !Function>} */141    this.on = {};  // event listeners142    /** @type {!Array.<!TextTrack>} */143    this.textTracks = [];144    this.currentTime = currentTime || 0;145    this.readyState = 0;146    this.playbackRate = 1;147    this.volume = 1;148    this.muted = false;149    this.loop = false;150    this.autoplay = false;151    this.paused = false;152    this.buffered = createFakeBuffered([]);153    this.src = '';154    this.offsetWidth = 1000;155    this.offsetHeight = 1000;156    /** @type {!jasmine.Spy} */157    this.addTextTrack =158        jasmine.createSpy('addTextTrack').and.callFake((kind, id) => {159          const track = new shaka.test.FakeTextTrack();160          this.textTracks.push(track);161          return track;162        });163    /** @type {!jasmine.Spy} */164    this.setMediaKeys =165        jasmine.createSpy('createMediaKeys').and.returnValue(Promise.resolve());166    /** @type {!jasmine.Spy} */167    this.addEventListener =168        jasmine.createSpy('addEventListener').and.callFake((name, callback) => {169          this.on[name] = callback;170        });171    /** @type {!jasmine.Spy} */172    this.removeEventListener = jasmine.createSpy('removeEventListener');173    /** @type {!jasmine.Spy} */174    this.removeAttribute = jasmine.createSpy('removeAttribute');175    /** @type {!jasmine.Spy} */176    this.load = jasmine.createSpy('load');177    /** @type {!jasmine.Spy} */178    this.play = jasmine.createSpy('play');179    /** @type {!jasmine.Spy} */180    this.pause = jasmine.createSpy('pause');181    /** @type {!jasmine.Spy} */182    this.dispatchEvent = jasmine.createSpy('dispatchEvent');183  }184};185/**186 * Creates a fake buffered ranges object.187 *188 * @param {!Array.<{start: number, end: number}>} ranges189 * @return {!TimeRanges}190 */191function createFakeBuffered(ranges) {192  return /** @type {!TimeRanges} */ ({193    length: ranges.length,194    start: (i) => {195      if (i >= 0 && i < ranges.length) {196        return ranges[i].start;197      }198      throw new Error('Unexpected index');199    },200    end: (i) => {201      if (i >= 0 && i < ranges.length) {202        return ranges[i].end;203      }204      throw new Error('Unexpected index');205    },206  });207}208/** @extends {shaka.media.PresentationTimeline} */209shaka.test.FakePresentationTimeline = class {210  constructor() {211    const getStart = jasmine.createSpy('getSeekRangeStart');212    const getEnd = jasmine.createSpy('getSeekRangeEnd');213    const getSafeStart = jasmine.createSpy('getSafeSeekRangeStart');214    getSafeStart.and.callFake((delay) => {215      const end = shaka.test.Util.invokeSpy(getEnd);216      return Math.min(shaka.test.Util.invokeSpy(getStart) + delay, end);217    });218    /** @type {!jasmine.Spy} */219    this.getDuration = jasmine.createSpy('getDuration');220    /** @type {!jasmine.Spy} */221    this.setDuration = jasmine.createSpy('setDuration');222    /** @type {!jasmine.Spy} */223    this.getDelay = jasmine.createSpy('getDelay');224    /** @type {!jasmine.Spy} */225    this.setDelay = jasmine.createSpy('setDelay');226    /** @type {!jasmine.Spy} */227    this.getPresentationStartTime =228        jasmine.createSpy('getPresentationStartTime');229    /** @type {!jasmine.Spy} */230    this.setClockOffset = jasmine.createSpy('setClockOffset');231    /** @type {!jasmine.Spy} */232    this.setStatic = jasmine.createSpy('setStatic');233    /** @type {!jasmine.Spy} */234    this.notifySegments = jasmine.createSpy('notifySegments');235    /** @type {!jasmine.Spy} */236    this.notifyMaxSegmentDuration =237        jasmine.createSpy('notifyMaxSegmentDuration');238    /** @type {!jasmine.Spy} */239    this.isLive = jasmine.createSpy('isLive');240    /** @type {!jasmine.Spy} */241    this.isInProgress = jasmine.createSpy('isInProgress');242    /** @type {!jasmine.Spy} */243    this.getSegmentAvailabilityStart =244        jasmine.createSpy('getSegmentAvailabilityStart');245    /** @type {!jasmine.Spy} */246    this.getSegmentAvailabilityEnd =247        jasmine.createSpy('getSegmentAvailabilityEnd');248    /** @type {!jasmine.Spy} */249    this.getSeekRangeStart = getStart;250    /** @type {!jasmine.Spy} */251    this.getSafeSeekRangeStart = getSafeStart;252    /** @type {!jasmine.Spy} */253    this.getSeekRangeEnd = getEnd;254    /** @type {!jasmine.Spy} */255    this.getMaxSegmentDuration = jasmine.createSpy('getMaxSegmentDuration');256  }257};258/** @extends {shaka.media.Playhead} */259shaka.test.FakePlayhead = class {260  constructor() {261    /** @type {!jasmine.Spy} */262    this.release = jasmine.createSpy('release');263    /** @type {!jasmine.Spy} */264    this.setRebufferingGoal = jasmine.createSpy('setRebufferingGoal');265    /** @type {!jasmine.Spy} */266    this.setStartTime = jasmine.createSpy('setStartTime');267    /** @type {!jasmine.Spy} */268    this.getTime = jasmine.createSpy('getTime').and.returnValue(0);269    /** @type {!jasmine.Spy} */270    this.setBuffering = jasmine.createSpy('setBuffering');271    /** @type {!jasmine.Spy} */272    this.getPlaybackRate =273        jasmine.createSpy('getPlaybackRate').and.returnValue(1);274    /** @type {!jasmine.Spy} */275    this.setPlaybackRate = jasmine.createSpy('setPlaybackRate');276  }277};278/** @extends {TextTrack} */279shaka.test.FakeTextTrack = class {280  constructor() {281    // The compiler knows TextTrack.cues is const, and we lied and said we282    // "extend" TextTrack, so it won't let us assign to cues here.  But we283    // must, because this fake is a from-scratch implementation of the API.284    // This cast-hack works around the issue.285    /** @type {!Array.<TextTrackCue>} */286    const cues = [];287    (/** @type {?} */(this))['cues'] = cues;288    /** @type {!jasmine.Spy} */289    this.addCue = jasmine.createSpy('addCue').and.callFake((cue) => {290      cues.push(cue);291    });292    /** @type {!jasmine.Spy} */293    this.removeCue = jasmine.createSpy('removeCue').and.callFake((cue) => {294      const idx = cues.indexOf(cue);295      expect(idx).not.toBeLessThan(0);296      cues.splice(idx, 1);297    });298  }299};300/**301 * Create a test-focused closed caption parser that requires the creator to302 * provide behaviours for the underlying spies. If no behaviour is provided all303 * calls to the parser will act as NO-OPs.304 *305 * @implements {shaka.media.IClosedCaptionParser}306 * @final307 */308shaka.test.FakeClosedCaptionParser = class {309  constructor() {310    /** @type {!jasmine.Spy} */311    this.initSpy = jasmine.createSpy('init');312    /** @type {!jasmine.Spy} */313    this.parseFromSpy = jasmine.createSpy('parseFrom');314    /** @type {!jasmine.Spy} */315    this.resetSpy = jasmine.createSpy('reset');316  }317  /** @override */318  init() {319    return shaka.test.Util.invokeSpy(this.initSpy);320  }321  /** @override */322  parseFrom(data) {323    return shaka.test.Util.invokeSpy(this.parseFromSpy, data);324  }325  /** @override */326  reset() {327    return shaka.test.Util.invokeSpy(this.resetSpy);328  }329};330/** @extends {shaka.media.SegmentIndex} */331shaka.test.FakeSegmentIndex = class {332  constructor() {333    /** @type {!jasmine.Spy} */334    this.release = jasmine.createSpy('release');335    /** @type {!jasmine.Spy} */336    this.find = jasmine.createSpy('find').and.returnValue(null);337    /** @type {!jasmine.Spy} */338    this.get = jasmine.createSpy('get').and.returnValue(null);339    /** @type {!jasmine.Spy} */340    this.offset = jasmine.createSpy('offset');341    /** @type {!jasmine.Spy} */342    this.merge = jasmine.createSpy('merge');343    /** @type {!jasmine.Spy} */344    this.replace = jasmine.createSpy('replace');345    /** @type {!jasmine.Spy} */346    this.evict = jasmine.createSpy('evict');347    /** @type {!jasmine.Spy} */348    this.fit = jasmine.createSpy('fit');349    /** @type {!jasmine.Spy} */350    this.updateEvery = jasmine.createSpy('updateEvery');351    /** @type {!jasmine.Spy} */352    this[Symbol.iterator] = jasmine.createSpy('Symbol.iterator')353        .and.callFake(() => this.getIteratorForTime(0));354    /** @type {!jasmine.Spy} */355    this.getIteratorForTime = jasmine.createSpy('getIteratorForTime')356        .and.callFake((time) => {357          let nextPosition = this.find(time);358          return {359            next: () => {360              const value = this.get(nextPosition++);361              return {362                value,363                done: !value,364              };365            },366            current: () => {367              return this.get(nextPosition - 1);368            },369            seek: (time) => {370              nextPosition = this.find(time);371              return this.get(nextPosition++);372            },373          };374        });375  }376};377/** @extends {shaka.media.Transmuxer} */378shaka.test.FakeTransmuxer = class {379  constructor() {380    const output = {381      data: new Uint8Array(),382      captions: [],383    };384    /** @type {!jasmine.Spy} */385    this.destroy =386        jasmine.createSpy('destroy').and.returnValue(Promise.resolve());387    /** @type {!jasmine.Spy} */388    this.transmux =389        jasmine.createSpy('transmux').and.returnValue(Promise.resolve(output));390  }...

Full Screen

Full Screen

shipping.test.js

Source:shipping.test.js Github

copy

Full Screen

...13define(['squire', 'ko', 'jquery', 'uiRegistry', 'jquery/validate'], function (Squire, ko, $, registry) {14    'use strict';15    var injector = new Squire(),16        modalStub = {17            openModal: jasmine.createSpy(),18            closeModal: jasmine.createSpy()19        },20        mocks = {21            'Magento_Customer/js/model/customer': {22                isLoggedIn: ko.observable()23            },24            'Magento_Customer/js/model/address-list': ko.observableArray(),25            'Magento_Checkout/js/model/address-converter': jasmine.createSpy(),26            'Magento_Checkout/js/model/quote': {27                isVirtual: jasmine.createSpy(),28                shippingMethod: ko.observable(),29                /**30                 * Stub31                 */32                shippingAddress: function () {33                    return {34                        'countryId': 'AD'35                    };36                }37            },38            'Magento_Checkout/js/action/create-shipping-address': jasmine.createSpy().and.returnValue(39                jasmine.createSpyObj('newShippingAddress', ['getKey'])40            ),41            'Magento_Checkout/js/action/select-shipping-address': jasmine.createSpy(),42            'Magento_Checkout/js/model/shipping-rates-validator': jasmine.createSpy(),43            'Magento_Checkout/js/model/shipping-address/form-popup-state': {44                isVisible: ko.observable()45            },46            'Magento_Checkout/js/model/shipping-service': jasmine.createSpyObj('service', ['getShippingRates']),47            'Magento_Checkout/js/action/select-shipping-method': jasmine.createSpy(),48            'Magento_Checkout/js/model/shipping-rate-registry': jasmine.createSpy(),49            'Magento_Checkout/js/action/set-shipping-information': jasmine.createSpy(),50            'Magento_Checkout/js/model/step-navigator': jasmine.createSpyObj('navigator', ['registerStep']),51            'Magento_Ui/js/modal/modal': jasmine.createSpy('modal').and.returnValue(modalStub),52            'Magento_Checkout/js/model/checkout-data-resolver': jasmine.createSpyObj(53                'dataResolver',54                ['resolveShippingAddress']55            ),56            'Magento_Checkout/js/checkout-data': jasmine.createSpyObj(57                'checkoutData',58                ['setSelectedShippingAddress', 'setNewCustomerShippingAddress', 'setSelectedShippingRate']59            ),60            'Magento_Ui/js/lib/registry/registry': registry,61            'Magento_Checkout/js/model/shipping-rate-service': jasmine.createSpy()62        },63        obj;64    beforeEach(function (done) {65        injector.mock(mocks);66        injector.require(['Magento_Checkout/js/view/shipping'], function (Constr) {67            obj = new Constr({68                provider: 'provName',69                name: '',70                parentName: 'test',71                index: '',72                popUpForm: {73                    options: {74                        buttons: {75                            save: {},76                            cancel: {}77                        }78                    }79                }80            });81            done();82        });83    });84    afterEach(function () {85        try {86            injector.clean();87            injector.remove();88        } catch (e) {}89    });90    describe('Magento_Checkout/js/view/shipping', function () {91        describe('"navigate" method', function () {92            it('Check for return value.', function () {93                var step = {94                    isVisible: ko.observable(false)95                };96                expect(obj.navigate(step)).toBeUndefined();97                expect(step.isVisible()).toBe(true);98            });99        });100        describe('"getPopUp" method', function () {101            it('Check for return value.', function () {102                expect(obj.getPopUp()).toBe(modalStub);103                expect(mocks['Magento_Ui/js/modal/modal']).toHaveBeenCalled();104                mocks['Magento_Ui/js/modal/modal'].calls.reset();105            });106            it('Check on single modal call', function () {107                expect(obj.getPopUp()).toBe(modalStub);108                expect(mocks['Magento_Ui/js/modal/modal']).not.toHaveBeenCalled();109            });110        });111        describe('"showFormPopUp" method', function () {112            it('Check method call.', function () {113                expect(obj.showFormPopUp()).toBeUndefined();114                expect(obj.isFormPopUpVisible()).toBeTruthy();115                expect(modalStub.openModal).toHaveBeenCalled();116            });117        });118        describe('"saveNewAddress" method', function () {119            it('Check method call with invalid form data.', function () {120                obj.source = {121                    get: jasmine.createSpy().and.returnValue(true),122                    set: jasmine.createSpy(),123                    trigger: jasmine.createSpy()124                };125                expect(obj.saveNewAddress()).toBeUndefined();126                expect(obj.isNewAddressAdded()).toBeFalsy();127                expect(modalStub.closeModal).not.toHaveBeenCalled();128            });129            it('Check method call with valid form data.', function () {130                obj.source = {131                    get: jasmine.createSpy().and.returnValues(true, false, {}),132                    set: jasmine.createSpy(),133                    trigger: jasmine.createSpy()134                };135                expect(obj.saveNewAddress()).toBeUndefined();136                expect(obj.isNewAddressAdded()).toBeTruthy();137                expect(modalStub.closeModal).toHaveBeenCalled();138            });139        });140        describe('"selectShippingMethod" method', function () {141            it('Check method call.', function () {142                var shippingMethod = {143                    'carrier_code': 'carrier',144                    'method_code': 'method'145                };146                expect(obj.selectShippingMethod(shippingMethod)).toBeTruthy();147                expect(mocks['Magento_Checkout/js/checkout-data'].setSelectedShippingRate)148                    .toHaveBeenCalledWith('carrier_method');149            });150        });151        describe('"setShippingInformation" method', function () {152            it('Check method call.', function () {153                spyOn(obj, 'validateShippingInformation').and.returnValue(false);154                expect(obj.setShippingInformation()).toBeUndefined();155            });156        });157        describe('"validateShippingInformation" method', function () {158            it('Check method call on negative cases.', function () {159                var country = {160                    'indexedOptions': {161                        'AD':162                            {163                                label: 'Andorra',164                                labeltitle: 'Andorra',165                                value: 'AD'166                            }167                    }168                };169                registry.set('test.shippingAddress.shipping-address-fieldset.country_id', country);170                registry.set('checkout.errors', {});171                obj.source = {172                    get: jasmine.createSpy().and.returnValue(true),173                    set: jasmine.createSpy(),174                    trigger: jasmine.createSpy()175                };176                expect(obj.validateShippingInformation()).toBeFalsy();177                expect(obj.errorValidationMessage()).toBe(178                    'The shipping method is missing. Select the shipping method and try again.'179                );180                spyOn(mocks['Magento_Checkout/js/model/quote'], 'shippingMethod').and.returnValue(true);181                spyOn(mocks['Magento_Customer/js/model/customer'], 'isLoggedIn').and.returnValue(true);182                expect(obj.validateShippingInformation()).toBeFalsy();183            });184            it('Check method call on positive case.', function () {185                $('body').append('<form data-role="email-with-possible-login">' +186                    '<input type="text" name="username" />' +187                    '</form>');188                obj.source = {189                    get: jasmine.createSpy().and.returnValue(true),190                    set: jasmine.createSpy(),191                    trigger: jasmine.createSpy()192                };193                obj.isFormInline = false;194                spyOn(mocks['Magento_Checkout/js/model/quote'], 'shippingMethod').and.returnValue(true);195                spyOn(mocks['Magento_Customer/js/model/customer'], 'isLoggedIn').and.returnValue(false);196                spyOn($.fn, 'valid').and.returnValue(true);197                expect(obj.validateShippingInformation()).toBeTruthy();198            });199        });200        describe('"triggerShippingDataValidateEvent" method', function () {201            it('Check method call.', function () {202                obj.source = {203                    get: jasmine.createSpy().and.returnValue(true),204                    set: jasmine.createSpy(),205                    trigger: jasmine.createSpy()206                };207                expect(obj.triggerShippingDataValidateEvent()).toBeUndefined();208            });209        });210    });...

Full Screen

Full Screen

mocks.js

Source:mocks.js Github

copy

Full Screen

1;(function() {2  Pusher.Mocks = {3    getScriptRequest: function() {4      return {5        send: jasmine.createSpy("send"),6        cleanup: jasmine.createSpy("cleanup")7      };8    },9    getDocument: function() {10      return {11        location: {12          protocol: "http:"13        },14        getElementsByTagName: jasmine.createSpy("getElementsByTagName"),15        createElement: jasmine.createSpy("createElement"),16        addEventListener: jasmine.createSpy("addEventListener")17      };18    },19    getDocumentElement: function() {20      return {21        setAttribute: jasmine.createSpy("setAttribute"),22        addEventListener: jasmine.createSpy("addEventListener"),23        insertBefore: jasmine.createSpy("insertBefore"),24        appendChild: jasmine.createSpy("appendChild")25      };26    },27    getXHR: function() {28      return {29        open: jasmine.createSpy("open"),30        send: jasmine.createSpy("send"),31        abort: jasmine.createSpy("abort"),32        setRequestHeader: jasmine.createSpy("setRequestHeader")33      };34    },35    getWebSocket: function() {36      return {37        send: jasmine.createSpy("send"),38        close: jasmine.createSpy("close")39      };40    },41    getHTTPSocket: function() {42      var socket = new Pusher.EventsDispatcher();43      socket.close = jasmine.createSpy("close");44      socket.sendRaw = jasmine.createSpy("sendRaw");45      socket.onChunk = jasmine.createSpy("onChunk");46      socket.onClose = jasmine.createSpy("onClose");47      socket.reconnect = jasmine.createSpy("sendRaw");48      return socket;49    },50    getHTTPRequest: function(method, url) {51      var request = new Pusher.EventsDispatcher();52      request.start = jasmine.createSpy("start");53      request.close = jasmine.createSpy("close");54      request.method = method;55      request.url = url;56      return request;57    },58    getDependencies: function() {59      return {60        load: jasmine.createSpy("load"),61        getRoot: jasmine.createSpy("getRoot"),62        getPath: jasmine.createSpy("getPath")63      };64    },65    getJSONPSender: function() {66      return {67        send: jasmine.createSpy("send")68      };69    },70    getTimeline: function() {71      return {72        log: jasmine.createSpy("log"),73        error: jasmine.createSpy("error"),74        info: jasmine.createSpy("info"),75        debug: jasmine.createSpy("debug"),76        send: jasmine.createSpy("send"),77        isEmpty: jasmine.createSpy("isEmpty"),78        generateUniqueID: jasmine.createSpy("generateUniqueID")79      };80    },81    getTimelineSender: function() {82      var sender = {83        isEncrypted: jasmine.createSpy("isEncrypted"),84        send: jasmine.createSpy("send")85      };86      sender.getEncrypted = jasmine.createSpy("getEncrypted").andReturn(sender);87      return sender;88    },89    getTransport: function() {90      var transport = new Pusher.EventsDispatcher();91      transport.handlesActivityChecks = jasmine.createSpy("handlesActivityChecks")92        .andReturn(false);93      transport.supportsPing = jasmine.createSpy("supportsPing")94        .andReturn(false);95      transport.initialize = jasmine.createSpy("initialize")96        .andCallFake(function() {97          transport.state = "initializing";98          transport.emit("initializing");99        });100      transport.connect = jasmine.createSpy("connect");101      transport.send = jasmine.createSpy("send")102        .andReturn(true);103      transport.ping = jasmine.createSpy("ping");104      transport.close = jasmine.createSpy("close");105      transport.state = undefined;106      return transport;107    },108    getTransportManager: function(alive) {109      return {110        isAlive: jasmine.createSpy("isAlive").andReturn(alive !== false),111        reportDeath: jasmine.createSpy("reportDeath")112      };113    },114    getAssistantToTheTransportManager: function(transport) {115      return {116        createConnection: jasmine.createSpy("createConnection")117          .andReturn(transport || Pusher.Mocks.getTransport()),118        isSupported: jasmine.createSpy("isSupported")119          .andReturn(true)120      };121    },122    getTransportClass: function(supported, transport) {123      var klass = {};124      klass.isSupported = jasmine.createSpy("isSupported")125        .andReturn(supported);126      klass.createConnection = jasmine.createSpy("createConnection")127        .andReturn(transport || Pusher.Mocks.getTransport());128      return klass;129    },130    getHandshake: function(transport, callback) {131      return {132        close: jasmine.createSpy("close"),133        _transport: transport,134        _callback: callback135      };136    },137    getStrategy: function(isSupported) {138      var strategy = new Pusher.EventsDispatcher();139      strategy._abort = jasmine.createSpy();140      strategy._forceMinPriority = jasmine.createSpy();141      strategy._callback = null;142      strategy.isSupported = jasmine.createSpy("isSupported")143        .andReturn(isSupported);144      strategy.connect = jasmine.createSpy("connect")145        .andCallFake(function(minPriority, callback) {146          strategy._callback = callback;147          return {148            abort: strategy._abort,149            forceMinPriority: strategy._forceMinPriority150          };151        });152      return strategy;153    },154    getStrategies: function(isSupportedList) {155      var strategies = [];156      for (var i = 0; i < isSupportedList.length; i++) {157        strategies.push(Pusher.Mocks.getStrategy(isSupportedList[i]));158      }159      return strategies;160    },161    getConnection: function() {162      var connection = new Pusher.EventsDispatcher();163      connection.initialize = jasmine.createSpy("initialize");164      connection.connect = jasmine.createSpy("connect");165      connection.handlesActivityChecks = jasmine.createSpy("handlesActivityChecks")166        .andReturn(false);167      connection.supportsPing = jasmine.createSpy("supportsPing")168        .andReturn(false);169      connection.send = jasmine.createSpy("send")170        .andReturn(true);171      connection.ping = jasmine.createSpy("ping")172        .andReturn(true);173      connection.send_event = jasmine.createSpy("send_event")174        .andReturn(true);175      connection.close = jasmine.createSpy("close");176      return connection;177    },178    getConnectionManager: function(socket_id) {179      var manager = new Pusher.EventsDispatcher();180      manager.socket_id = socket_id || "1.1";181      manager.connect = jasmine.createSpy("connect");182      manager.disconnect = jasmine.createSpy("disconnect");183      manager.send_event = jasmine.createSpy("send_event");184      manager.isEncrypted = jasmine.createSpy("isEncrypted").andReturn(false);185      return manager;186    },187    getPusher: function(config) {188      var pusher = new Pusher.EventsDispatcher();189      pusher.config = config;190      pusher.send_event = jasmine.createSpy("send_event");191      return pusher;192    },193    getChannel: function(name) {194      var channel = new Pusher.EventsDispatcher();195      channel.name = name;196      channel.authorize = jasmine.createSpy("authorize");197      channel.disconnect = jasmine.createSpy("disconnect");198      channel.handleEvent = jasmine.createSpy("handleEvent");199      channel.subscribe = jasmine.createSpy("subscribe");200      channel.unsubscribe = jasmine.createSpy("unsubscribe");201      return channel;202    },203    getAuthorizer: function() {204      var authorizer = {};205      authorizer._callback = null;206      authorizer.authorize = jasmine.createSpy("authorize").andCallFake(function(_, callback) {207        authorizer._callback = callback;208      });209      return authorizer;210    }211  };...

Full Screen

Full Screen

shipping-estimation.test.js

Source:shipping-estimation.test.js Github

copy

Full Screen

...6define(['squire', 'ko'], function (Squire, ko) {7    'use strict';8    var injector = new Squire(),9        checkoutProvider = {10            on: jasmine.createSpy()11        },12        mocks = {13            'Magento_Checkout/js/action/select-shipping-address': jasmine.createSpy(),14            'Magento_Checkout/js/model/address-converter': {15                formAddressDataToQuoteAddress: jasmine.createSpy()16            },17            'Magento_Checkout/js/model/cart/estimate-service': jasmine.createSpy(),18            'Magento_Checkout/js/checkout-data': jasmine.createSpy(),19            'Magento_Checkout/js/model/shipping-rates-validator': {20                bindChangeHandlers: jasmine.createSpy()21            },22            'uiRegistry': {23                async: jasmine.createSpy().and.returnValue(function (callback) {24                    callback(checkoutProvider);25                }),26                create: jasmine.createSpy(),27                get: jasmine.createSpy(),28                set: jasmine.createSpy()29            },30            'Magento_Checkout/js/model/quote': {31                isVirtual: jasmine.createSpy(),32                shippingAddress: jasmine.createSpy()33            },34            'Magento_Checkout/js/model/checkout-data-resolver': {35                resolveEstimationAddress: jasmine.createSpy()36            },37            'mage/validation': jasmine.createSpy()38        },39        obj;40    beforeEach(function (done) {41        injector.mock(mocks);42        injector.require(['Magento_Checkout/js/view/cart/shipping-estimation'], function (Constr) {43            obj = new Constr({44                provider: 'provName',45                name: '',46                index: ''47            });48            done();49        });50    });51    afterEach(function () {52        try {53            injector.clean();54            injector.remove();55        } catch (e) {}56    });57    describe('Magento_Checkout/js/view/cart/shipping-estimation', function () {58        describe('"initElement" method', function () {59            it('Check for return value and element that initiated.', function () {60                var element = jasmine.createSpyObj('element', ['initContainer']);61                expect(obj.initElement(element)).toBe(obj);62                expect(mocks['Magento_Checkout/js/model/shipping-rates-validator'].bindChangeHandlers)63                    .not.toHaveBeenCalled();64            });65            it('Check shipping rates validator call.', function () {66                var element = {67                    index: 'address-fieldsets',68                    elems: ko.observable(),69                    initContainer: jasmine.createSpy()70                };71                spyOn(element.elems, 'subscribe');72                obj.initElement(element);73                expect(mocks['Magento_Checkout/js/model/shipping-rates-validator'].bindChangeHandlers)74                    .toHaveBeenCalledWith(element.elems(), true, 500);75                expect(element.elems.subscribe)76                    .toHaveBeenCalledWith(jasmine.any(Function));77            });78        });79        describe('"getEstimationInfo" method', function () {80            it('Check for invalid form data.', function () {81                obj.source = {82                    get: jasmine.createSpy().and.returnValue(true),83                    set: jasmine.createSpy(),84                    trigger: jasmine.createSpy()85                };86                expect(obj.getEstimationInfo()).toBeUndefined();87                expect(obj.source.get).toHaveBeenCalledWith('params.invalid');88                expect(obj.source.get).not.toHaveBeenCalledWith('shippingAddress');89                expect(obj.source.set).toHaveBeenCalledWith('params.invalid', false);90                expect(obj.source.trigger).toHaveBeenCalledWith('shippingAddress.data.validate');91                expect(mocks['Magento_Checkout/js/action/select-shipping-address']).not.toHaveBeenCalled();92                obj.source = {};93            });94            it('Check for vaild form data.', function () {95                obj.source = {96                    get: jasmine.createSpy().and.returnValues(false, {}),97                    set: jasmine.createSpy(),98                    trigger: jasmine.createSpy()99                };100                expect(obj.getEstimationInfo()).toBeUndefined();101                expect(obj.source.get).toHaveBeenCalledWith('params.invalid');102                expect(obj.source.get).toHaveBeenCalledWith('shippingAddress');103                expect(obj.source.set).toHaveBeenCalledWith('params.invalid', false);104                expect(obj.source.trigger).toHaveBeenCalledWith('shippingAddress.data.validate');105                expect(mocks['Magento_Checkout/js/action/select-shipping-address']).toHaveBeenCalled();106                obj.source = {};107            });108        });109    });...

Full Screen

Full Screen

color-picker.test.js

Source:color-picker.test.js Github

copy

Full Screen

...26        it('Should call spectrum on $input with disabled configuration if view model disabled', function () {27            var value = {28                    configStuffInHere: true29                },30                valueAccessor = jasmine.createSpy().and.returnValue(value),31                viewModel = {32                    disabled: jasmine.createSpy().and.returnValue(true)33                };34            $.fn.spectrum = jasmine.createSpy();35            $input = jasmine.createSpy();36            ko.bindingHandlers.colorPicker.init($input, valueAccessor, null, viewModel);37            expect(value.change).toEqual(jasmine.any(Function));38            expect(value.hide).toEqual(jasmine.any(Function));39            expect(value.show).toEqual(jasmine.any(Function));40            expect(value.change).toBe(value.hide);41            expect($.fn.spectrum.calls.allArgs()).toEqual([[value], ['disable']]);42            expect(viewModel.disabled).toHaveBeenCalled();43            $.fn.init = jasmine.createSpy().and.returnValue($.fn);44            ko.bindingHandlers.colorPicker.init($input, valueAccessor, null, viewModel);45            expect($.fn.init).toHaveBeenCalledWith($input, undefined);46        });47        it('Should call spectrum on $input with extra configuration if view model enabled', function () {48            var value = {49                    configStuffInHere: true50                },51                valueAccessor = jasmine.createSpy().and.returnValue(value),52                viewModel = {53                    disabled: jasmine.createSpy().and.returnValue(false)54                };55            $.fn.spectrum = jasmine.createSpy();56            $input = jasmine.createSpy();57            ko.bindingHandlers.colorPicker.init($input, valueAccessor, null, viewModel);58            expect(value.change).toEqual(jasmine.any(Function));59            expect(value.hide).toEqual(jasmine.any(Function));60            expect(value.show).toEqual(jasmine.any(Function));61            expect(value.change).toBe(value.hide);62            expect($.fn.spectrum.calls.allArgs()).toEqual([[value], ['enable']]);63            expect(viewModel.disabled).toHaveBeenCalled();64            $.fn.init = jasmine.createSpy().and.returnValue($.fn);65            ko.bindingHandlers.colorPicker.init($input, valueAccessor, null, viewModel);66            expect($.fn.init).toHaveBeenCalledWith($input, undefined);67        });68        it('Verify config value is empty when reset colorpicker intput', function () {69            var value = {70                    configStuffInHere: true,71                    value: jasmine.createSpy().and.returnValue(undefined)72                },73                valueAccessor = jasmine.createSpy().and.returnValue(value),74                viewModel = {75                    disabled: jasmine.createSpy().and.returnValue(false)76                };77            $.fn.spectrum = jasmine.createSpy();78            $input = jasmine.createSpy();79            ko.bindingHandlers.colorPicker.update($input, valueAccessor, null, viewModel);80            expect($.fn.spectrum).toHaveBeenCalledTimes(1);81            expect(valueAccessor().value).toHaveBeenCalledTimes(4);82            value.value = jasmine.createSpy().and.returnValue('');83            ko.bindingHandlers.colorPicker.update($input, valueAccessor, null, viewModel);84            expect($.fn.spectrum).toHaveBeenCalledTimes(3);85            expect(valueAccessor().value).toHaveBeenCalledTimes(5);86        });87    });...

Full Screen

Full Screen

withCredentials.js

Source:withCredentials.js Github

copy

Full Screen

...3describe("swagger-js plugin - withCredentials", () => {4  it("should have no effect by default", () => {5    const system = {6      fn: {7        fetch: createSpy().andReturn(Promise.resolve())8      },9      getConfigs: () => ({})10    }11    const oriExecute = createSpy()12    const loadedFn = loaded(oriExecute, system)13    loadedFn()14    expect(oriExecute.calls.length).toBe(1)15    expect(system.fn.fetch.withCredentials).toBe(undefined)16  })17  it("should allow setting flag to true via config", () => {18    const system = {19      fn: {20        fetch: createSpy().andReturn(Promise.resolve())21      },22      getConfigs: () => ({23        withCredentials: true24      })25    }26    const oriExecute = createSpy()27    const loadedFn = loaded(oriExecute, system)28    loadedFn()29    expect(oriExecute.calls.length).toBe(1)30    expect(system.fn.fetch.withCredentials).toBe(true)31  })32  33  it("should allow setting flag to false via config", () => {34    const system = {35      fn: {36        fetch: createSpy().andReturn(Promise.resolve())37      },38      getConfigs: () => ({39        withCredentials: false40      })41    }42    const oriExecute = createSpy()43    const loadedFn = loaded(oriExecute, system)44    loadedFn()45    expect(oriExecute.calls.length).toBe(1)46    expect(system.fn.fetch.withCredentials).toBe(false)47  })48  49   it("should allow setting flag to true via config as string", () => {50    // for query string config51    const system = {52      fn: {53        fetch: createSpy().andReturn(Promise.resolve())54      },55      getConfigs: () => ({56        withCredentials: "true"57      })58    }59    const oriExecute = createSpy()60    const loadedFn = loaded(oriExecute, system)61    loadedFn()62    expect(oriExecute.calls.length).toBe(1)63    expect(system.fn.fetch.withCredentials).toBe(true)64  })65  66  it("should allow setting flag to false via config as string", () => {67    // for query string config68    const system = {69      fn: {70        fetch: createSpy().andReturn(Promise.resolve())71      },72      getConfigs: () => ({73        withCredentials: "false"74      })75    }76    const oriExecute = createSpy()77    const loadedFn = loaded(oriExecute, system)78    loadedFn()79    expect(oriExecute.calls.length).toBe(1)80    expect(system.fn.fetch.withCredentials).toBe(false)81  })...

Full Screen

Full Screen

scoresMock.js

Source:scoresMock.js Github

copy

Full Screen

...18            published: false,19            index: 120        }],21        scoreboard: scoreboard,22        remove: jasmine.createSpy('scoreRemoveSpy'),23        load: jasmine.createSpy('scoreLoadSpy'),24        pollSheets: jasmine.createSpy('scorePollSheetsSpy').and.returnValue($q.when()),25        update: jasmine.createSpy('scoreUpdateSpy'),26        _update: jasmine.createSpy('score_UpdateSpy'),27        save: jasmine.createSpy('scoreSaveSpy'),28        enableAutoRefresh: jasmine.createSpy('enableAutoRefresh'),29        disableAutoRefresh: jasmine.createSpy('disableAutoRefresh'),30        getRankings: jasmine.createSpy('getRankings').and.returnValue(scoreboard),31    };...

Full Screen

Full Screen

Jest Testing Tutorial

LambdaTest’s Jest Testing Tutorial covers step-by-step guides around Jest with code examples to help you be proficient with the Jest framework. The Jest tutorial has chapters to help you learn right from the basics of Jest framework to code-based tutorials around testing react apps with Jest, perform snapshot testing, import ES modules and more.

Chapters

  1. What is Jest Framework
  2. Advantages of Jest - Jest has 3,898,000 GitHub repositories, as mentioned on its official website. Learn what makes Jest special and why Jest has gained popularity among the testing and developer community.
  3. Jest Installation - All the prerequisites and set up steps needed to help you start Jest automation testing.
  4. Using Jest with NodeJS Project - Learn how to leverage Jest framework to automate testing using a NodeJS Project.
  5. Writing First Test for Jest Framework - Get started with code-based tutorial to help you write and execute your first Jest framework testing script.
  6. Jest Vocabulary - Learn the industry renowned and official jargons of the Jest framework by digging deep into the Jest vocabulary.
  7. Unit Testing with Jest - Step-by-step tutorial to help you execute unit testing with Jest framework.
  8. Jest Basics - Learn about the most pivotal and basic features which makes Jest special.
  9. Jest Parameterized Tests - Avoid code duplication and fasten automation testing with Jest using parameterized tests. Parameterization allows you to trigger the same test scenario over different test configurations by incorporating parameters.
  10. Jest Matchers - Enforce assertions better with the help of matchers. Matchers help you compare the actual output with the expected one. Here is an example to see if the object is acquired from the correct class or not. -

|<p>it('check_object_of_Car', () => {</p><p> expect(newCar()).toBeInstanceOf(Car);</p><p> });</p>| | :- |

  1. Jest Hooks: Setup and Teardown - Learn how to set up conditions which needs to be followed by the test execution and incorporate a tear down function to free resources after the execution is complete.
  2. Jest Code Coverage - Unsure there is no code left unchecked in your application. Jest gives a specific flag called --coverage to help you generate code coverage.
  3. HTML Report Generation - Learn how to create a comprehensive HTML report based on your Jest test execution.
  4. Testing React app using Jest Framework - Learn how to test your react web-application with Jest framework in this detailed Jest tutorial.
  5. Test using LambdaTest cloud Selenium Grid - Run your Jest testing script over LambdaTest cloud-based platform and leverage parallel testing to help trim down your test execution time.
  6. Snapshot Testing for React Front Ends - Capture screenshots of your react based web-application and compare them automatically for visual anomalies with the help of Jest tutorial.
  7. Bonus: Import ES modules with Jest - ES modules are also known as ECMAScript modules. Learn how to best use them by importing in your Jest testing scripts.
  8. Jest vs Mocha vs Jasmine - Learn the key differences between the most popular JavaScript-based testing frameworks i.e. Jest, Mocha, and Jasmine.
  9. Jest FAQs(Frequently Asked Questions) - Explore the most commonly asked questions around Jest framework, with their answers.

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