How to use testMiddleware method in Cypress

Best JavaScript code snippet using cypress

test.request.js

Source:test.request.js Github

copy

Full Screen

...20          }21        }, function () {});22      });23      it('defaults to {}', function (done) {24        testMiddleware('GET', '/', function (req, res) {25          expect(req.headers).to.be.an('object');26          expect(Object.keys(req.headers)).to.have.length(0);27          done();28        });29      });30    });31    describe('req.xhr', function () {32      it('returns `true` when `X-Requested-With` is set to `XMLHttpRequest`', function (done) {33        var gt = new GhostTrain();34        gt.get('/', function (req, res) {35          expect(req.xhr).to.be.equal(true);36          done();37        });38        gt.request('GET', '/', { headers: {'X-Requested-With': 'xmlhttprequest'}}, function () {});39      });40      it('returns `false` when `X-Requested-With` is unset', function (done) {41        var gt = new GhostTrain();42        gt.get('/', function (req, res) {43          expect(req.xhr).to.be.equal(false);44          done();45        });46        gt.request('GET', '/');47      });48    });49    describe('req.route', function () {50      it('contains the matching route', function (done) {51        testMiddleware('GET', '/dinosaurtown', function (req, res) {52          expect(req.route.path).to.be.equal('/dinosaurtown');53          expect(req.route.method).to.be.equal('get');54          done();55        });56      });57    });58    describe('req.method', function () {59      ['GET', 'POST', 'PUT', 'DELETE', 'HEAD', 'PATCH'].forEach(function (verb) {60        it('returns correct method for ' + verb, function (done) {61          testMiddleware(verb, '/', function (req, res) {62            expect(req.method).to.be.equal(verb);63            done();64          });65        });66      });67    });68    describe('req.url, req.originalUrl', function () {69      it('returns URL for relative URL with query', function (done) {70        testMiddleware('get', '/path/to', '/path/to?q=myquery', function (req, res) {71          expect(req.url).to.be.equal('/path/to?q=myquery');72          expect(req.originalUrl).to.be.equal('/path/to?q=myquery');73          done();74        });75      });76      it('returns URL for relative URL with out query', function (done) {77        testMiddleware('get', '/path/to', '/path/to', function (req, res) {78          expect(req.url).to.be.equal('/path/to');79          expect(req.originalUrl).to.be.equal('/path/to');80          done();81        });82      });83      it('returns URL for absolute URL with query', function (done) {84        testMiddleware('get', '/path/to', 'http://domain.com:9999/path/to?q=myquery', function (req, res) {85          expect(req.url).to.be.equal('/path/to?q=myquery');86          expect(req.originalUrl).to.be.equal('/path/to?q=myquery');87          done();88        });89      });90      it('returns URL for absolute URL with out query', function (done) {91        testMiddleware('get', '/path/to', 'http://domain.com:9999/path/to', function (req, res) {92          expect(req.url).to.be.equal('/path/to');93          expect(req.originalUrl).to.be.equal('/path/to');94          done();95        });96      });97    });98    describe('req.path', function () {99      it('has correct path for relative url', function (done) {100        testMiddleware('GET', '/nightly/browser', function (req, res) {101          expect(req.path).to.be.equal('/nightly/browser');102          done();103        });104      });105      it('has correct path for relative url with query params', function (done) {106        testMiddleware('GET', '/nightly/browser', '/nightly/browser?q=myquery', function (req, res) {107          expect(req.path).to.be.equal('/nightly/browser');108          done();109        });110      });111      it('has correct path for absolute url', function (done) {112        testMiddleware('GET', '/nightly/browser', 'http://domain.com/nightly/browser', function (req, res) {113          expect(req.path).to.be.equal('/nightly/browser');114          done();115        });116      });117    });118    describe('req.protocol', function () {119      it('returns correct protocol for http', function (done) {120        testMiddleware('GET', '/path/firefox', 'http://mozilla.org/path/firefox', function (req, res) {121          expect(req.protocol).to.be.equal('http');122          done();123        });124      });125      it('returns correct protocol for ftp', function (done) {126        testMiddleware('GET', '/path/firefox', 'ftp://mozilla.org/path/firefox', function (req, res) {127          expect(req.protocol).to.be.equal('ftp');128          done();129        });130      });131      it('returns correct protocol for https', function (done) {132        testMiddleware('GET', '/path/firefox', 'https://mozilla.org/path/firefox', function (req, res) {133          expect(req.protocol).to.be.equal('https');134          done();135        });136      });137      it('returns local page\'s protocol for relative links', function (done) {138        testMiddleware('GET', '/path/to/yeah', function (req, res) {139          var protocol = 'window' in this ? window.location.protocol : '';140          expect(req.protocol).to.be.equal(protocol.replace(':',''));141          done();142        });143      });144    });145    describe('req.secure', function () {146      it('secure is true for https', function (done) {147        testMiddleware('GET', '/path/firefox', 'https://mozilla.org/path/firefox', function (req, res) {148          expect(req.secure).to.be.equal(true);149          done();150        });151      });152      it('returns false for non-https', function (done) {153        var count = 3;154        testMiddleware('GET', '/path/firefox', 'http://mozilla.org/path/firefox', function (req, res) {155          expect(req.secure).to.be.equal(false);156          complete();157        });158        testMiddleware('GET', '/path/firefox', 'http://mozilla.org/path/firefox', function (req, res) {159          expect(req.secure).to.be.equal(false);160          complete();161        });162        testMiddleware('GET', '/path/firefox', 'http://mozilla.org/path/firefox', function (req, res) {163          expect(req.secure).to.be.equal(false);164          complete();165        });166        function complete () { if (!--count) done() }167      });168    });169    describe('req.params', function () {170      it('populates req.params array from :params in route', function (done) {171        var gt = new GhostTrain();172        gt.get('/users/:field1/:field2/:id', function (req, res) {173          expect(req.params.field1).to.be.equal('long');174          expect(req.params.field2).to.be.equal('user');175          expect(req.params.id).to.be.equal('12345');176          res.send();177        });178        gt.request('GET', '/users/long/user/12345', function (err, res) {179          done();180        });181      });182      it('populates req.params array from regex in route', function (done) {183        var gt = new GhostTrain();184        gt.get(/users\/([^\/]*)\/u(ser)\/([^\/]*)/, function (req, res) {185          expect(req.params[0]).to.be.equal('long');186          expect(req.params[1]).to.be.equal('ser');187          expect(req.params[2]).to.be.equal('12345');188          res.send();189        });190        gt.request('GET', '/users/long/user/12345', function (err, res) {191          done();192        });193      });194    });195    describe('req.query', function () {196      it('returns query object', function (done) {197        var gt = new GhostTrain();198        gt.get('/users', function (req, res) {199          expect(req.query.name).to.be.equal('justin timberlake');200          expect(req.query.password).to.be.equal('smoothpop');201          expect(Object.keys(req.query)).to.have.length(2);202          res.send();203        });204        gt.request('GET', '/users?name=justin%20timberlake&password=smoothpop', function (err, res, body) {205          done();206        });207      });208      it('defaults to an empty {}', function (done) {209        var gt = new GhostTrain();210        gt.get('/users', function (req, res) {211          expect(req.query).to.be.an('object');212          expect(Object.keys(req.query)).to.have.length(0);213          res.send();214        });215        gt.request('GET', '/users', function (err, res, body) {216          done();217        });218      });219    });220    describe('req.body', function () {221      it('populates req.body on POST', function (done) {222        var gt = new GhostTrain();223        gt.post('/users', function (req, res) {224          expect(req.body.name).to.be.equal('Justin Timberlake');225          expect(req.body.jams).to.be.equal('FutureSex/LoveSounds');226          res.send();227        });228        gt.request('POST', '/users', {229          body: {230            name: 'Justin Timberlake',231            jams: 'FutureSex/LoveSounds'232          }233        }, function (err, res) {234          done();235        });236      });237      it('it is an empty object by default', function (done) {238        var gt = new GhostTrain();239        gt.get('/users/:id', function (req, res) {240          expect(req.body).to.be.an('object');241          res.send();242        });243        gt.request('GET', '/users/12345', function (err, res) {244          done();245        });246      });247    });248  });249  describe('req.param()', function () {250    it('returns params, falls back to body, then query', function (done) {251      var gt = new GhostTrain();252      gt.post('/users/:id/show/', function (req, res) {253        expect(req.param('id')).to.be.equal('12345');254        expect(req.param('name')).to.be.equal('dudedude');255        expect(req.param('q')).to.be.equal('myquery');256        res.send();257      });258      gt.request('POST', '/users/12345/show?q=myquery&id=123', {259        body: { 'id': 789, 'name': 'dudedude' }260      }, function (err, res, body) {261        done();262      });263    });264  });265  describe('req.range()', function () {266    it('returns correct range');267  });268  describe('req.is()', function () {269    it('returns true for matching content types', function (done) {270      var gt = new GhostTrain();271      gt.get('/', function (req, res) {272        expect(req.is('json')).to.be.equal(true);273        expect(req.is('application/json')).to.be.equal(true);274        expect(req.is('application/*')).to.be.equal(true);275        expect(req.is('html')).to.be.equal(false);276        expect(req.is('text/html')).to.be.equal(false);277        expect(req.is('text/*')).to.be.equal(false);278        res.send();279      });280      gt.request('GET', '/', {281        headers: {282          'Content-Type': 'application/json'283        }284      }, function () {285        done();286      });287    });288    it('returns false for not matching content types', function (done) {289      var gt = new GhostTrain();290      gt.get('/', function (req, res) {291        expect(req.is('html')).to.be.equal(false);292        expect(req.is('text/html')).to.be.equal(false);293        expect(req.is('text/*')).to.be.equal(false);294        expect(req.is('')).to.be.equal(false);295        res.send();296      });297      gt.request('GET', '/', {298        headers: {299          'Content-Type': 'application/json'300        }301      }, function () {302        done();303      });304    });305  });306  describe('req.get(), req.header()', function () {307    ['get', 'header'].forEach(function (method) {308      it('returns correct header for name for req.' + method + '()', function (done) {309        var gt = new GhostTrain();310        gt.get('/', function (req, res) {311          expect(req[method]('Content-Type')).to.be.equal('text/html');312          done();313        });314        gt.request('GET', '/', { headers: { 'Content-Type': 'text/html' }}, function () {});315      });316      it('returns undefined for unset headers for req.' + method + '()', function (done) {317        var gt = new GhostTrain();318        gt.get('/', function (req, res) {319          expect(req[method]('X-Some-Header')).to.be.equal(undefined);320          done();321        });322        gt.request('GET', '/', { headers: { 'Content-Type': 'text/html' }}, function () {});323      });324    });325  });326  describe('Unsupported properties', function () {327    ['subdomains', 'stale', 'fresh', 'ip', 'ips', 'auth',328      'accepted', 'acceptedEncodings', 'acceptedCharsets', 'acceptedLanguages'].forEach(function (prop) {329      if (getSupported()) {330        it('accessing `req.' + prop + '` throws on supported browsers', function (done) {331          testMiddleware('GET', '/', function (req, res) {332            expect(function () {333              req[prop];334            }).to.throwError();335            done();336          });337        });338      } else {339        it('accessing `req.' + prop + '` is undefined because browser does not support `Object.defineProperty`', function (done) {340          testMiddleware('GET', '/', function (req, res) {341            expect(req[prop]).to.be.equal(undefined);342            done();343          });344        });345      }346    });347  });348  describe('Unsupported methods', function () {349    ['accepts', 'acceptsEncoding', 'acceptsCharset', 'acceptsLanguage'].forEach(function (prop) {350      it('Calling `req.' + prop + '()` throws', function (done) {351        testMiddleware('GET', '/', function (req, res) {352          expect(function () {353            req[prop]();354          }).to.throwError();355          done();356        });357      });358    });359  });...

Full Screen

Full Screen

model.middleware.test.js

Source:model.middleware.test.js Github

copy

Full Screen

1'use strict';2/**3 * Test dependencies.4 */5const start = require('./common');6const assert = require('power-assert');7const mongoose = start.mongoose;8const Schema = mongoose.Schema;9describe('model middleware', function() {10  var db;11  before(function() {12    db = start();13  });14  after(function(done) {15    db.close(done);16  });17  it('post save', function(done) {18    var schema = new Schema({19      title: String20    });21    var called = 0;22    schema.post('save', function(obj) {23      assert.equal(obj.title, 'Little Green Running Hood');24      assert.equal(this.title, 'Little Green Running Hood');25      assert.equal(called, 0);26      called++;27    });28    schema.post('save', function(obj) {29      assert.equal(obj.title, 'Little Green Running Hood');30      assert.equal(this.title, 'Little Green Running Hood');31      assert.equal(called, 1);32      called++;33    });34    schema.post('save', function(obj, next) {35      assert.equal(obj.title, 'Little Green Running Hood');36      assert.equal(called, 2);37      called++;38      next();39    });40    const TestMiddleware = db.model('TestPostSaveMiddleware', schema);41    const test = new TestMiddleware({title: 'Little Green Running Hood'});42    test.save(function(err) {43      assert.ifError(err);44      assert.equal(test.title, 'Little Green Running Hood');45      assert.equal(called, 3);46      done();47    });48  });49  it('sync error in post save (gh-3483)', function(done) {50    var schema = new Schema({51      title: String52    });53    schema.post('save', function() {54      throw new Error('woops!');55    });56    const TestMiddleware = db.model('gh3483_post', schema);57    const test = new TestMiddleware({ title: 'Test' });58    test.save(function(err) {59      assert.ok(err);60      assert.equal(err.message, 'woops!');61      done();62    });63  });64  it('pre hook promises (gh-3779)', function(done) {65    const schema = new Schema({66      title: String67    });68    let calledPre = 0;69    schema.pre('save', function() {70      return new Promise(resolve => {71        setTimeout(() => {72          ++calledPre;73          resolve();74        }, 100);75      });76    });77    const TestMiddleware = db.model('gh3779_pre', schema);78    const test = new TestMiddleware({ title: 'Test' });79    test.save(function(err) {80      assert.ifError(err);81      assert.equal(calledPre, 1);82      done();83    });84  });85  it('post hook promises (gh-3779)', function(done) {86    const schema = new Schema({87      title: String88    });89    schema.post('save', function(doc) {90      return new Promise(resolve => {91        setTimeout(() => {92          doc.title = 'From Post Save';93          resolve();94        }, 100);95      });96    });97    const TestMiddleware = db.model('gh3779_post', schema);98    const test = new TestMiddleware({ title: 'Test' });99    test.save(function(err, doc) {100      assert.ifError(err);101      assert.equal(doc.title, 'From Post Save');102      done();103    });104  });105  it('validate middleware runs before save middleware (gh-2462)', function(done) {106    var schema = new Schema({107      title: String108    });109    var count = 0;110    schema.pre('validate', function(next) {111      assert.equal(count++, 0);112      next();113    });114    schema.pre('save', function(next) {115      assert.equal(count++, 1);116      next();117    });118    var Book = db.model('gh2462', schema);119    Book.create({}, function() {120      assert.equal(count, 2);121      done();122    });123  });124  it('works', function(done) {125    var schema = new Schema({126      title: String127    });128    var called = 0;129    schema.pre('init', function() {130      called++;131    });132    schema.pre('save', function(next) {133      called++;134      next(new Error('Error 101'));135    });136    schema.pre('remove', function(next) {137      called++;138      next();139    });140    mongoose.model('TestMiddleware', schema);141    var TestMiddleware = db.model('TestMiddleware');142    var test = new TestMiddleware();143    test.init({ title: 'Test' }, function(err) {144      assert.ifError(err);145      assert.equal(called, 1);146      test.save(function(err) {147        assert.ok(err instanceof Error);148        assert.equal(err.message, 'Error 101');149        assert.equal(called, 2);150        test.remove(function(err) {151          assert.ifError(err);152          assert.equal(called, 3);153          done();154        });155      });156    });157  });158  describe('post init hooks', function() {159    it('success', function() {160      const schema = new Schema({ title: String, loadedAt: Date });161      schema.pre('init', pojo => {162        assert.equal(pojo.constructor.name, 'Object'); // Plain object before init163      });164      const now = new Date();165      schema.post('init', doc => {166        assert.ok(doc instanceof mongoose.Document); // Mongoose doc after init167        doc.loadedAt = now;168      });169      const Test = db.model('TestPostInitMiddleware', schema);170      return Test.create({ title: 'Casino Royale' }).171        then(doc => Test.findById(doc)).172        then(doc => assert.equal(doc.loadedAt.valueOf(), now.valueOf()));173    });174    it('with errors', function() {175      const schema = new Schema({ title: String });176      const swallowedError = new Error('will not show');177      // acquit:ignore:start178      swallowedError.$expected = true;179      // acquit:ignore:end180      // init hooks do **not** handle async errors or any sort of async behavior181      schema.pre('init', () => Promise.reject(swallowedError));182      schema.post('init', () => { throw Error('will show'); });183      const Test = db.model('PostInitBook', schema);184      return Test.create({ title: 'Casino Royale' }).185        then(doc => Test.findById(doc)).186        catch(error => assert.equal(error.message, 'will show'));187    });188  });189  it('gh-1829', function(done) {190    var childSchema = new mongoose.Schema({191      name: String192    });193    var childPreCalls = 0;194    var childPreCallsByName = {};195    var parentPreCalls = 0;196    childSchema.pre('save', function(next) {197      childPreCallsByName[this.name] = childPreCallsByName[this.name] || 0;198      ++childPreCallsByName[this.name];199      ++childPreCalls;200      next();201    });202    var parentSchema = new mongoose.Schema({203      name: String,204      children: [childSchema]205    });206    parentSchema.pre('save', function(next) {207      ++parentPreCalls;208      next();209    });210    var Parent = db.model('gh-1829', parentSchema, 'gh-1829');211    var parent = new Parent({212      name: 'Han',213      children: [214        {name: 'Jaina'},215        {name: 'Jacen'}216      ]217    });218    parent.save(function(error) {219      assert.ifError(error);220      assert.equal(childPreCalls, 2);221      assert.equal(childPreCallsByName.Jaina, 1);222      assert.equal(childPreCallsByName.Jacen, 1);223      assert.equal(parentPreCalls, 1);224      parent.children[0].name = 'Anakin';225      parent.save(function(error) {226        assert.ifError(error);227        assert.equal(childPreCalls, 4);228        assert.equal(childPreCallsByName.Anakin, 1);229        assert.equal(childPreCallsByName.Jaina, 1);230        assert.equal(childPreCallsByName.Jacen, 2);231        assert.equal(parentPreCalls, 2);232        done();233      });234    });235  });236  it('sync error in pre save (gh-3483)', function(done) {237    var schema = new Schema({238      title: String239    });240    schema.post('save', function() {241      throw new Error('woops!');242    });243    const TestMiddleware = db.model('gh3483_pre', schema);244    const test = new TestMiddleware({ title: 'Test' });245    test.save(function(err) {246      assert.ok(err);247      assert.equal(err.message, 'woops!');248      done();249    });250  });251  it('sync error in pre save after next() (gh-3483)', function(done) {252    var schema = new Schema({253      title: String254    });255    var called = 0;256    schema.pre('save', function(next) {257      next();258      // This error will not get reported, because you already called next()259      throw new Error('woops!');260    });261    schema.pre('save', function(next) {262      ++called;263      next();264    });265    const TestMiddleware = db.model('gh3483_pre_2', schema);266    const test = new TestMiddleware({ title: 'Test' });267    test.save(function(error) {268      assert.ifError(error);269      assert.equal(called, 1);270      done();271    });272  });273  it('validate + remove', function(done) {274    var schema = new Schema({275      title: String276    });277    var preValidate = 0,278        postValidate = 0,279        preRemove = 0,280        postRemove = 0;281    schema.pre('validate', function(next) {282      ++preValidate;283      next();284    });285    schema.pre('remove', function(next) {286      ++preRemove;287      next();288    });289    schema.post('validate', function(doc) {290      assert.ok(doc instanceof mongoose.Document);291      ++postValidate;292    });293    schema.post('remove', function(doc) {294      assert.ok(doc instanceof mongoose.Document);295      ++postRemove;296    });297    var Test = db.model('TestPostValidateMiddleware', schema);298    var test = new Test({title: 'banana'});299    test.save(function(err) {300      assert.ifError(err);301      assert.equal(preValidate, 1);302      assert.equal(postValidate, 1);303      assert.equal(preRemove, 0);304      assert.equal(postRemove, 0);305      test.remove(function(err) {306        assert.ifError(err);307        assert.equal(preValidate, 1);308        assert.equal(postValidate, 1);309        assert.equal(preRemove, 1);310        assert.equal(postRemove, 1);311        done();312      });313    });314  });...

Full Screen

Full Screen

syncLocationWithSearch.test.js

Source:syncLocationWithSearch.test.js Github

copy

Full Screen

...40      const action = {41        type: LOCATION_CHANGE,42        payload: { location },43      };44      const resultAction = testMiddleware(action);45      expect(resultAction).toEqual(action);46      expect(mockDispatch).toHaveBeenCalledWith(47        searchQueryUpdate(namespace, location.query, true)48      );49    });50    it('dispatches searchQueryReset if there is a POP (back) but pathname has not changed', () => {51      const namespace = LITERATURE_NS;52      const location = {53        pathname: LITERATURE,54        search: '?size=10&q=guy',55        query: { size: 10, q: 'guy' },56      };57      const router = { location };58      const search = fromJS({59        namespaces: {60          [namespace]: {61            query: { size: 10, q: 'dude' },62          },63        },64      });65      const getState = () => ({ search, router });66      const mockNextFuncThatMirrors = action => action;67      const mockDispatch = jest.fn();68      const testMiddleware = middleware({ getState, dispatch: mockDispatch })(69        mockNextFuncThatMirrors70      );71      const action = {72        type: LOCATION_CHANGE,73        payload: { location, action: 'POP' },74      };75      const resultAction = testMiddleware(action);76      expect(resultAction).toEqual(action);77      expect(mockDispatch).toHaveBeenCalledWith(searchQueryReset(namespace));78    });79    it('dispatches searchQueryUpdate when isFirstRendering even if namespace query equals to location query', () => {80      const namespace = LITERATURE_NS;81      const location = {82        pathname: LITERATURE,83        search: '?size=10&q=dude',84        query: { size: 10, q: 'dude' },85      };86      const router = { location };87      const search = fromJS({88        namespaces: {89          [namespace]: {90            query: { size: 10, q: 'dude' },91          },92        },93      });94      const getState = () => ({ search, router });95      const mockNextFuncThatMirrors = action => action;96      const mockDispatch = jest.fn();97      const testMiddleware = middleware({ getState, dispatch: mockDispatch })(98        mockNextFuncThatMirrors99      );100      const action = {101        type: LOCATION_CHANGE,102        payload: { location, isFirstRendering: true },103      };104      const resultAction = testMiddleware(action);105      expect(resultAction).toEqual(action);106      expect(mockDispatch).toHaveBeenCalledWith(107        searchQueryUpdate(namespace, location.query, true)108      );109    });110    it('dispatches newSearch for previous namespace when pathname changes', () => {111      const namespace = LITERATURE_NS;112      const location = {113        pathname: LITERATURE,114        search: '?size=10&q=dude',115        query: { size: 10, q: 'dude' },116      };117      const router = { location };118      const getState = () => ({ router }); // previous state119      const mockNextFuncThatMirrors = action => action;120      const mockDispatch = jest.fn();121      const testMiddleware = middleware({ getState, dispatch: mockDispatch })(122        mockNextFuncThatMirrors123      );124      const action = {125        type: LOCATION_CHANGE,126        payload: { location: { pathname: '/another-thing' } },127      };128      const resultAction = testMiddleware(action);129      expect(resultAction).toEqual(action);130      expect(mockDispatch).toHaveBeenCalledWith(newSearch(namespace));131    });132    it('does not dispatch newSearch if pathname does not change', () => {133      const namespace = LITERATURE_NS;134      const location = {135        pathname: LITERATURE,136        search: '?size=10&q=dude',137        query: { size: 10, q: 'dude' },138      };139      const search = fromJS({140        namespaces: {141          [namespace]: {142            query: { size: 10, q: 'dude' },143          },144        },145      });146      const router = { location };147      const getState = () => ({ router, search }); // previous state148      const mockNextFuncThatMirrors = action => action;149      const mockDispatch = jest.fn();150      const testMiddleware = middleware({ getState, dispatch: mockDispatch })(151        mockNextFuncThatMirrors152      );153      const action = {154        type: LOCATION_CHANGE,155        payload: { location: { pathname: LITERATURE } },156      };157      const resultAction = testMiddleware(action);158      expect(resultAction).toEqual(action);159      expect(mockDispatch).not.toHaveBeenCalledWith(newSearch(namespace));160    });161    it('does not dispatch newSearch if previous pathname is not a search page', () => {162      const namespace = LITERATURE_NS;163      const location = {164        pathname: '/whatever',165        search: '',166        query: {},167      };168      const router = { location };169      const getState = () => ({ router }); // previous state170      const mockNextFuncThatMirrors = action => action;171      const mockDispatch = jest.fn();172      const testMiddleware = middleware({ getState, dispatch: mockDispatch })(173        mockNextFuncThatMirrors174      );175      const action = {176        type: LOCATION_CHANGE,177        payload: { location: { pathname: '/another-thing' } },178      };179      const resultAction = testMiddleware(action);180      expect(resultAction).toEqual(action);181      expect(mockDispatch).not.toHaveBeenCalledWith(newSearch(namespace));182    });183    it('does not dispatch SEARCH_QUERY_UPDATE if pathame is not search page but location query is not sync with search namespace query', () => {184      const namespace = LITERATURE_NS;185      const location = {186        pathname: `/${LITERATURE}/12345`,187        search: '?size=10&q=guy', // although this won't happen188        query: { size: 10, q: 'guy' },189      };190      const router = { location };191      const search = fromJS({192        namespaces: {193          [namespace]: {194            query: { size: 10, q: 'dude' },195          },196        },197      });198      const getState = () => ({ search, router });199      const mockNextFuncThatMirrors = action => action;200      const mockDispatch = jest.fn();201      const testMiddleware = middleware({ getState, dispatch: mockDispatch })(202        mockNextFuncThatMirrors203      );204      const action = {205        type: LOCATION_CHANGE,206        payload: { location },207      };208      const resultAction = testMiddleware(action);209      expect(resultAction).toEqual(action);210      expect(mockDispatch).not.toHaveBeenCalled();211    });212    it('does not dispatch SEARCH_QUERY_UPDATE if pathame is search page but location query is sync with search namespace query', () => {213      const namespace = LITERATURE_NS;214      const location = {215        pathname: LITERATURE,216        search: '?size=10&q=guy&ui-param=ignored',217        query: { size: 10, q: 'guy', 'ui-param': 'ignored' },218      };219      const router = { location };220      const search = fromJS({221        namespaces: {222          [namespace]: {223            query: { size: 10, q: 'guy', 'ui-param': 'also-ignored' },224          },225        },226      });227      const getState = () => ({ search, router });228      const mockNextFuncThatMirrors = action => action;229      const mockDispatch = jest.fn();230      const testMiddleware = middleware({ getState, dispatch: mockDispatch })(231        mockNextFuncThatMirrors232      );233      const action = {234        type: LOCATION_CHANGE,235        payload: { location },236      };237      const resultAction = testMiddleware(action);238      expect(resultAction).toEqual(action);239      expect(mockDispatch).not.toHaveBeenCalled();240    });241  });242  describe('on anything', () => {243    it('returns next(the action)', () => {244      const getState = () => ({});245      const mockNextFuncThatMirrors = action => action;246      const mockDispatch = jest.fn();247      const testMiddleware = middleware({ getState, dispatch: mockDispatch })(248        mockNextFuncThatMirrors249      );250      const action = { type: 'WHATEVER' };251      const resultAction = testMiddleware(action);252      expect(mockDispatch).not.toHaveBeenCalled();253      expect(resultAction).toEqual(action);254    });255  });...

Full Screen

Full Screen

reduxSocketIOSpec.js

Source:reduxSocketIOSpec.js Github

copy

Full Screen

...200      describe('and the socket is already present', () => {201        it('calls connect on the initialized socket', () => {202          const testMiddleware = middleware.socketio(mockSocket);203          // initialize / connect204          testMiddleware(store)(next)(action);205          testMiddleware(store)(next)({ type: `${DEFAULT_ID}_DISCONNECT` });206          // reconnect207          testMiddleware(store)(next)(action);208          expect(mockSocket.connect).to.have.been.called;209        });210      });211    });212    describe('when the socket is connected', () => {213      describe('and a client request is sent', () => {214        beforeEach(() => {215          action = Object.assign({}, action, { payload: { host: 'test', port: 1234 } });216        });217        it('dispatches the action', () => {218          const event = {219            action: 'TEST',220            dispatch: sinon.spy()221          };222          const testMiddleware = middleware.socketio(null, [event]);223          testMiddleware(store)(next)(action);224          testMiddleware(store)(next)({ type: 'TEST' });225          expect(event.dispatch).to.have.been.called;226        });227        describe('when the dispatch property is not present', () => {228          it('calls emit from the default handler', () => {229            const event = { action: 'TEST' };230            const testMiddleware = middleware.socketio(mockSocket, [event]);231            testMiddleware(store)(next)(action);232            testMiddleware(store)(next)({ type: 'TEST' });233            expect(mockSocket.emit).to.have.been.called;234          });235        });236      });237      describe('and SocketName_DISCONNECT is called', () => {238        beforeEach(() => {239          action = Object.assign({}, action, { payload: { host: 'test', port: 1234 } });240        });241        it('calls .disconnect on the socket', () => {242          const testMiddleware = middleware.socketio(mockSocket);243          testMiddleware(store)(next)(action);244          testMiddleware(store)(next)({ type: `${DEFAULT_ID}_DISCONNECT` });245          expect(mockSocket.disconnect).to.have.been.called;246        });247        it('sets the status to uninitialized', () => {248          const testMiddleware = middleware.socketio(mockSocket);249          testMiddleware(store)(next)(action);250          testMiddleware(store)(next)({ type: `${DEFAULT_ID}_DISCONNECT` });251          expect(middleware.getInitStatus(DEFAULT_ID)).to.equal(false);252        });253      });254    });255  });...

Full Screen

Full Screen

table.tests.js

Source:table.tests.js Github

copy

Full Screen

...44    45    it('allows chaining of configuration functions', function () {46        tableFactory().use(function () {}).use(function () {}).read(function () {}).use(function () {});        47    })48    function testMiddleware(req, res, next) { }...

Full Screen

Full Screen

tableRouter.tests.js

Source:tableRouter.tests.js Github

copy

Full Screen

...37        // expect(router.stack[1].route.stack.length).to.equal(4);38        // expect(router.stack[1].route.stack[1].handle).to.equal(testMiddleware);39        // expect(router.stack[1].route.stack[2].handle).to.equal(testMiddleware);40    });41    function testMiddleware(req, res, next) { }...

Full Screen

Full Screen

siswa.js

Source:siswa.js Github

copy

Full Screen

1const express = require(`express`)2const app = express()3app.use(express.json())4// call siswa controller5let siswaController = require("../controllers/siswaController")6// call testMiddleware7let testMiddleware = require("../middlewares/testMiddleware")8let authorization = require("../middlewares/authorization")9let uploadImage = require("../middlewares/uploadImage")10// end-point get data siswa11app.get("/", [testMiddleware.middleware1, testMiddleware.middleware2,12    authorization.authorization13], 14    siswaController.getDataSiswa)15// end-point add data siswa16app.post("/", [17    uploadImage.upload.single(`image`), authorization.authorization18], 19    siswaController.addDataSiswa)20// end-point edit siswa21app.put("/:id_siswa", [22    uploadImage.upload.single(`image`), authorization.authorization23], 24    siswaController.editDataSiswa)25// end-point delete siswa26app.delete("/:id_siswa", siswaController.deleteDataSiswa)...

Full Screen

Full Screen

test-middleware.js

Source:test-middleware.js Github

copy

Full Screen

1'use strict';2var TestMiddleware = {3  results: {},4  extraConfiguration: function(resource) {5    TestMiddleware.results.extraConfiguration = true;6  }7};8TestMiddleware.results.extraConfiguration = false;9var actions = ['create', 'list', 'read', 'update', 'delete', 'all'],10    milestones = ['start', 'auth', 'fetch', 'data', 'write', 'send', 'complete'];11actions.forEach(function(action) {12  TestMiddleware.results[action] = {};13  TestMiddleware[action] = {};14  milestones.forEach(function(milestone) {15    TestMiddleware.results[action][milestone] = false;16    TestMiddleware[action][milestone] = function(req, res, context) {17      TestMiddleware.results[action][milestone] = true;18      return context.continue;19    };20  });21});...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('My First Test', function() {2  it('Does not do much!', function() {3    cy.testMiddleware()4  })5})6Cypress.Commands.add('testMiddleware', () => {7  cy.window().then(win => {8    win.store.dispatch({ type: 'TEST' })9  })10})

Full Screen

Using AI Code Generation

copy

Full Screen

1import { testMiddleware } from 'cypress-middleware'2import { testMiddleware } from 'cypress-middleware'3import { testMiddleware } from 'cypress-middleware'4import { testMiddleware } from 'cypress-middleware'5import { testMiddleware } from 'cypress-middleware'6import { testMiddleware } from 'cypress-middleware'7import { testMiddleware } from 'cypress-middleware'8import { testMiddleware } from 'cypress-middleware'9import { testMiddleware } from 'cypress-middleware'10import { testMiddleware } from 'cypress-middleware'11import { testMiddleware } from 'cypress-middleware'12import { testMiddleware } from 'cypress-middleware'13import { testMiddleware } from 'cypress-middleware'14import { testMiddleware } from 'cypress-middleware'15import { testMiddleware } from 'cypress-middleware'16import { testMiddleware } from 'cypress-middleware'17import { testMiddleware } from 'cypress-middleware'18import { testMiddleware } from 'cypress-middleware'19import { testMiddleware } from 'cypress-middleware'20import { testMiddleware } from 'cypress-middleware'21testMiddleware()22import { testMiddleware } from 'cypress-middleware'23testMiddleware({

Full Screen

Using AI Code Generation

copy

Full Screen

1Cypress.Commands.add('testMiddleware', (url, method, body) => {2    cy.request({3        url: Cypress.env('baseUrl') + url,4        headers: {5        }6    }).then((response) => {7        expect(response.status).to.eq(200);8        expect(response.body).to.have.property('success');9        expect(response.body).to.have.property('data');10        expect(response.body.success).to.eq(true);11    });12});13describe('Test', () => {14    it('Test', () => {15        cy.testMiddleware('/api/v1/test', 'POST', { "name": "test" });16    });17});18{19}20const express = require('express');21const app = express();22const bodyParser = require('body-parser');23app.use(bodyParser.json());24app.use(bodyParser.urlencoded({ extended: true }));25app.post('/api/v1/test', function (req, res) {26    res.status(200).json({27    });28});29app.listen(3000, function () {30    console.log('Listening on port 3000!');31});

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('My First Test', function() {2  it('Does not do much!', function() {3    cy.testMiddleware();4  })5})6{7  "compilerOptions": {8  }9}10MIT © [Harrison Smith](

Full Screen

Using AI Code Generation

copy

Full Screen

1test('test', () => {2  cy.testMiddleware('testMiddleware', 'test')3})4Cypress.Commands.add('testMiddleware', (middleware, action) => {5  cy.window().then(win => {6    win.store.dispatch(middleware(action))7  })8})9Cypress.on('window:before:load', win => {10  win.store = createStore(11    applyMiddleware(testMiddleware)12})

Full Screen

Using AI Code Generation

copy

Full Screen

1describe("test", () => {2  it("test", () => {3    cy.testMiddleware();4  });5});6[MIT](LICENSE)

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('Test Cypress', () => {2  it('should be able to test', () => {3    cy.testMiddleware('test');4  });5});6Cypress.Commands.add('testMiddleware', (message) => {7  cy.then(() => {8    console.log(message);9  });10});

Full Screen

Using AI Code Generation

copy

Full Screen

1cy.testMiddleware('middleware_name', 'middleware_method', 'middleware_params', 'middleware_response');2cy.testMiddleware('middleware_name', 'middleware_method', 'middleware_params', 'middleware_response', 'middleware_response_code');3cy.testMiddleware('middleware_name', 'middleware_method', 'middleware_params', 'middleware_response', 'middleware_response_code', 'middleware_response_message');4cy.testMiddleware('middleware_name', 'middleware_method', 'middleware_params', 'middleware_response', 'middleware_response_code', 'middleware_response_message', 'middleware_response_data');5cy.testMiddleware('middleware_name', 'middleware_method', 'middleware_params', 'middleware_response', 'middleware_response_code', 'middleware_response_message', 'middleware_response_data', 'middleware_response_data_key');6cy.testMiddleware('middleware_name', 'middleware_method', 'middleware_params', 'middleware_response', 'middleware_response_code', 'middleware_response_message', 'middleware_response_data', 'middleware_response_data_key', 'middleware_response_data_key_value');7cy.testMiddleware('middleware_name', 'middleware_method', 'middleware_params', 'middleware_response', 'middleware_response_code', 'middleware_response_message', 'middleware_response_data', 'middleware_response_data_key', 'middleware_response_data_key_value', 'middleware_response_data_key_value_key');8cy.testMiddleware('middleware_name', 'middleware_method', 'middleware_params', 'middleware_response', 'middleware_response_code', 'middleware_response_message', 'middleware_response_data', 'middleware_response_data_key', 'middleware_response_data_key_value', 'middleware_response_data_key_value_key', 'middleware_response_data_key_value_key_value');9import 'cypress-middleware-test';10cy.testMiddleware('middleware_name', 'middleware_method', 'middleware_params', 'middleware_response', 'middleware_response_code', 'middleware_response_message', 'middleware_response_data',

Full Screen

Cypress Tutorial

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

Chapters:

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

Certification

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

YouTube

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

Run Cypress automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful