How to use supertest method in Cypress

Best JavaScript code snippet using cypress

edit-collection.spec.js

Source:edit-collection.spec.js Github

copy

Full Screen

1var swagger    = require('../../../'),2    expect     = require('chai').expect,3    _          = require('lodash'),4    files      = require('../../fixtures/files'),5    helper     = require('./helper');6describe('Edit Collection Mock', function() {7  ['patch', 'put', 'post'].forEach(function(method) {8    describe(method.toUpperCase(), function() {9      'use strict';10      var api;11      beforeEach(function() {12        api = _.cloneDeep(files.parsed.petStore);13        api.paths['/pets'][method] = api.paths['/pets'].post;14        api.paths['/pets/{PetName}/photos'][method] = api.paths['/pets/{PetName}/photos'].post;15      });16      // Modifies the "/pets" schema to allow an array of pets17      function arrayify() {18        var petParam = _.find(api.paths['/pets'][method].parameters, {name: 'PetData'});19        petParam.schema = {20          type: 'array',21          items: petParam.schema22        };23      }24      describe('Shared tests', function() {25        it('should add a new resource to the collection',26          function(done) {27            helper.initTest(api, function(supertest) {28              // Create a new pet29              supertest30                [method]('/api/pets')31                .send({Name: 'Fido', Type: 'dog'})32                .expect(201, '')33                .end(helper.checkResults(done, function() {34                  // Retrieve the pet35                  supertest36                    .get('/api/pets/Fido')37                    .expect(200, {Name: 'Fido', Type: 'dog'})38                    .end(helper.checkResults(done));39                }));40            });41          }42        );43        it('should add multiple resources to the collection',44          function(done) {45            arrayify();46            helper.initTest(api, function(supertest) {47              // Create some new pets48              supertest49                [method]('/api/pets')50                .send([{Name: 'Fido', Type: 'dog'}, {Name: 'Fluffy', Type: 'cat'}, {Name: 'Polly', Type: 'bird'}])51                .expect(201, '')52                .end(helper.checkResults(done, function() {53                  // Retrieve a pet by name54                  supertest55                    .get('/api/pets/Fluffy')56                    .expect(200, {Name: 'Fluffy', Type: 'cat'})57                    .end(helper.checkResults(done, function() {58                      // Retrieve all the pets59                      supertest60                        .get('/api/pets')61                        .expect(200, [62                          {Name: 'Fido', Type: 'dog'},63                          {Name: 'Fluffy', Type: 'cat'},64                          {Name: 'Polly', Type: 'bird'}65                        ])66                        .end(helper.checkResults(done));67                    }));68                }));69            });70          }71        );72        it('should add zero resources to the collection',73          function(done) {74            arrayify();75            helper.initTest(api, function(supertest) {76              // Save zero pets77              supertest78                [method]('/api/pets')79                .send([])80                .expect(201, '')81                .end(helper.checkResults(done, function() {82                  // Retrieve all the pets (empty array)83                  supertest84                    .get('/api/pets')85                    .expect(200, [])86                    .end(helper.checkResults(done));87                }));88            });89          }90        );91        it('should not return data if not specified in the Swagger API',92          function(done) {93            delete api.paths['/pets'][method].responses[201].schema;94            helper.initTest(api, function(supertest) {95              supertest96                [method]('/api/pets')97                .send({Name: 'Fido', Type: 'dog'})98                .expect(201, '')99                .end(helper.checkResults(done));100            });101          }102        );103        it('should return the new resource if the Swagger API schema is an object',104          function(done) {105            api.paths['/pets'][method].responses[201].schema = {};106            var dataStore = new swagger.MemoryDataStore();107            var resource = new swagger.Resource('/api/pets/Fluffy', {Name: 'Fluffy', Type: 'cat'});108            dataStore.save(resource, function() {109              helper.initTest(dataStore, api, function(supertest) {110                supertest111                  [method]('/api/pets')112                  .send({Name: 'Fido', Type: 'dog'})113                  .expect(201, {Name: 'Fido', Type: 'dog'})114                  .end(helper.checkResults(done));115              });116            });117          }118        );119        it('should return the first new resource if the Swagger API schema is an object',120          function(done) {121            api.paths['/pets'][method].responses[201].schema = {};122            arrayify();123            var dataStore = new swagger.MemoryDataStore();124            var resource = new swagger.Resource('/api/pets/Fluffy', {Name: 'Fluffy', Type: 'cat'});125            dataStore.save(resource, function() {126              helper.initTest(dataStore, api, function(supertest) {127                supertest128                  [method]('/api/pets')129                  .send([{Name: 'Fido', Type: 'dog'}, {Name: 'Polly', Type: 'bird'}])130                  .expect(201, {Name: 'Fido', Type: 'dog'})131                  .end(helper.checkResults(done));132              });133            });134          }135        );136        it('should return the first new resource if the Swagger API schema is a wrapped object',137          function(done) {138            // Wrap the "pet" definition in an envelope object139            api.paths['/pets'][method].responses[201].schema = {140              properties: {141                code: {type: 'integer', default: 42},142                message: {type: 'string', default: 'hello world'},143                error: {},144                result: _.cloneDeep(api.definitions.pet)145              }146            };147            arrayify();148            var dataStore = new swagger.MemoryDataStore();149            var resource = new swagger.Resource('/api/pets/Fluffy', {Name: 'Fluffy', Type: 'cat'});150            dataStore.save(resource, function() {151              helper.initTest(dataStore, api, function(supertest) {152                supertest153                  [method]('/api/pets')154                  .send([{Name: 'Fido', Type: 'dog'}, {Name: 'Polly', Type: 'bird'}])155                  .expect(201, {code: 42, message: 'hello world', result: {Name: 'Fido', Type: 'dog'}})156                  .end(helper.checkResults(done));157              });158            });159          }160        );161        it('should return the whole collection (including the new resource) if the Swagger API schema is an array',162          function(done) {163            api.paths['/pets'][method].responses[201].schema = {type: 'array', items: {}};164            var dataStore = new swagger.MemoryDataStore();165            var resource = new swagger.Resource('/api/pets/Fluffy', {Name: 'Fluffy', Type: 'cat'});166            dataStore.save(resource, function() {167              helper.initTest(dataStore, api, function(supertest) {168                supertest169                  [method]('/api/pets')170                  .send({Name: 'Fido', Type: 'dog'})171                  .expect(201, [{Name: 'Fluffy', Type: 'cat'}, {Name: 'Fido', Type: 'dog'}])172                  .end(helper.checkResults(done));173              });174            });175          }176        );177        it('should return the whole collection (including the new resources) if the Swagger API schema is an array',178          function(done) {179            arrayify();180            api.paths['/pets'][method].responses[201].schema = {type: 'array', items: {}};181            var dataStore = new swagger.MemoryDataStore();182            var resource = new swagger.Resource('/api/pets/Fluffy', {Name: 'Fluffy', Type: 'cat'});183            dataStore.save(resource, function() {184              helper.initTest(dataStore, api, function(supertest) {185                supertest186                  [method]('/api/pets')187                  .send([{Name: 'Fido', Type: 'dog'}, {Name: 'Polly', Type: 'bird'}])188                  .expect(201, [{Name: 'Fluffy', Type: 'cat'}, {Name: 'Fido', Type: 'dog'}, {Name: 'Polly', Type: 'bird'}])189                  .end(helper.checkResults(done));190              });191            });192          }193        );194        it('should return the whole collection (including the new resources) if the Swagger API schema is a wrapped array',195          function(done) {196            // Wrap the "pet" definition in an envelope object197            api.paths['/pets'][method].responses[201].schema = {198              properties: {199                code: {type: 'integer', default: 42},200                message: {type: 'string', default: 'hello world'},201                error: {},202                result: {type: 'array', items: _.cloneDeep(api.definitions.pet)}203              }204            };205            arrayify();206            var dataStore = new swagger.MemoryDataStore();207            var resource = new swagger.Resource('/api/pets/Fluffy', {Name: 'Fluffy', Type: 'cat'});208            dataStore.save(resource, function() {209              helper.initTest(dataStore, api, function(supertest) {210                supertest211                  [method]('/api/pets')212                  .send([{Name: 'Fido', Type: 'dog'}, {Name: 'Polly', Type: 'bird'}])213                  .expect(201, {214                    code: 42,215                    message: 'hello world',216                    result: [217                      {Name: 'Fluffy', Type: 'cat'},218                      {Name: 'Fido', Type: 'dog'},219                      {Name: 'Polly', Type: 'bird'}220                    ]221                  })222                  .end(helper.checkResults(done));223              });224            });225          }226        );227        it('should return `res.body` if already set by other middleware',228          function(done) {229            api.paths['/pets'][method].responses[201].schema = {type: 'array', items: {}};230            function messWithTheBody(req, res, next) {231              res.body = {message: 'Not the response you expected'};232              next();233            }234            helper.initTest(messWithTheBody, api, function(supertest) {235              supertest236                [method]('/api/pets')237                .send({Name: 'Fido', Type: 'dog'})238                .expect(201, {message: 'Not the response you expected'})239                .end(helper.checkResults(done));240            });241          }242        );243        it('should set the "Location" HTTP header to new resource\'s URL',244          function(done) {245            helper.initTest(api, function(supertest) {246              supertest247                [method]('/api/pets')248                .send({Name: 'Fido', Type: 'dog'})249                .expect(201, '')250                .expect('Location', '/api/pets/Fido')251                .end(helper.checkResults(done));252            });253          }254        );255        it('should set the "Location" HTTP header to the collection URL',256          function(done) {257            arrayify();258            helper.initTest(api, function(supertest) {259              supertest260                [method]('/api/pets')261                .send([{Name: 'Fido', Type: 'dog'}, {Name: 'Fluffy', Type: 'cat'}, {Name: 'Polly', Type: 'bird'}])262                .expect(201, '')263                .expect('Location', '/api/pets')264                .end(helper.checkResults(done));265            });266          }267        );268        it('should set the "Location" HTTP header to the collection URL, even though it\'s empty',269          function(done) {270            arrayify();271            helper.initTest(api, function(supertest) {272              supertest273                [method]('/api/pets')274                .send([])275                .expect(201, '')276                .expect('Location', '/api/pets')277                .end(helper.checkResults(done));278            });279          }280        );281        it('should not set the "Location" HTTP header if not specified in the Swagger API (single object)',282          function(done) {283            delete api.paths['/pets'][method].responses[201].headers;284            helper.initTest(api, function(supertest) {285              supertest286                [method]('/api/pets')287                .send({Name: 'Fido', Type: 'dog'})288                .expect(201, '')289                .end(helper.checkResults(done, function(res) {290                  expect(res.headers.location).to.be.undefined;291                  done();292                }));293            });294          }295        );296        it('should not set the "Location" HTTP header if not specified in the Swagger API (array)',297          function(done) {298            delete api.paths['/pets'][method].responses[201].headers;299            arrayify();300            helper.initTest(api, function(supertest) {301              supertest302                [method]('/api/pets')303                .send([{Name: 'Fido', Type: 'dog'}, {Name: 'Fluffy', Type: 'cat'}, {Name: 'Polly', Type: 'bird'}])304                .expect(201, '')305                .end(helper.checkResults(done, function(res) {306                  expect(res.headers.location).to.be.undefined;307                  done();308                }));309            });310          }311        );312        it('should return a 500 error if a DataStore open error occurs',313          function(done) {314            var dataStore = new swagger.MemoryDataStore();315            dataStore.__openDataStore = function(collection, callback) {316              setImmediate(callback, new Error('Test Error'));317            };318            helper.initTest(dataStore, api, function(supertest) {319              supertest320                [method]('/api/pets')321                .send({Name: 'Fido', Type: 'dog'})322                .expect(500)323                .end(function(err, res) {324                  if (err) {325                    return done(err);326                  }327                  expect(res.text).to.contain('Error: Test Error');328                  done();329                });330            });331          }332        );333        it('should return a 500 error if a DataStore update error occurs',334          function(done) {335            var dataStore = new swagger.MemoryDataStore();336            dataStore.__saveDataStore = function(collection, data, callback) {337              setImmediate(callback, new Error('Test Error'));338            };339            helper.initTest(dataStore, api, function(supertest) {340              supertest341                [method]('/api/pets')342                .send({Name: 'Fido', Type: 'dog'})343                .expect(500)344                .end(function(err, res) {345                  if (err) {346                    return done(err);347                  }348                  expect(res.text).to.contain('Error: Test Error');349                  done();350                });351            });352          }353        );354      });355      describe('Determining resource names (by data type)', function() {356        it('should support strings',357          function(done) {358            _.find(api.paths['/pets'][method].parameters, {name: 'PetData'}).schema = {type: 'string'};359            api.paths['/pets'][method].responses[201].schema = {type: 'string'};360            api.paths['/pets'][method].consumes = ['text/plain'];361            api.paths['/pets'][method].produces = ['text/plain'];362            helper.initTest(api, function(supertest) {363              supertest364                [method]('/api/pets')365                .set('Content-Type', 'text/plain')366                .send('I am Fido')367                .expect(201, 'I am Fido')368                .expect('Location', '/api/pets/I%20am%20Fido')369                .end(helper.checkResults(done));370            });371          }372        );373        it('should support empty strings',374          function(done) {375            _.find(api.paths['/pets'][method].parameters, {name: 'PetData'}).schema = {type: 'string'};376            api.paths['/pets'][method].responses[201].schema = {type: 'string'};377            api.paths['/pets'][method].consumes = ['text/plain'];378            api.paths['/pets'][method].produces = ['text/plain'];379            helper.initTest(api, function(supertest) {380              supertest381                [method]('/api/pets')382                .set('Content-Type', 'text/plain')383                .send('')384                .expect(201, '')385                .expect('Location', '/api/pets/')386                .end(helper.checkResults(done));387            });388          }389        );390        it('should support very large strings',391          function(done) {392            _.find(api.paths['/pets'][method].parameters, {name: 'PetData'}).schema = {type: 'string'};393            api.paths['/pets'][method].responses[201].schema = {type: 'string'};394            api.paths['/pets/{PetName}'].get.responses[200].schema = {type: 'string'};395            api.paths['/pets'][method].consumes = ['text/plain'];396            api.paths['/pets'][method].produces = ['text/plain'];397            api.paths['/pets/{PetName}'].get.produces = ['text/plain'];398            helper.initTest(api, function(supertest) {399              var veryLongString = _.repeat('abcdefghijklmnopqrstuvwxyz', 5000);400              supertest401                [method]('/api/pets')402                .set('Content-Type', 'text/plain')403                .send(veryLongString)404                // The full value should be returned405                .expect(201, veryLongString)406                // The resource URL should be truncated to 2000 characters, for compatibility with some browsers407                .expect('Location', '/api/pets/' + veryLongString.substring(0, 2000))408                .end(helper.checkResults(done, function(res) {409                  // Verify that the full value was stored410                  supertest411                    .get(res.headers.location)412                    .expect(200, veryLongString)413                    .end(helper.checkResults(done));414                }));415            });416          }417        );418        it('should support numbers',419          function(done) {420            _.find(api.paths['/pets'][method].parameters, {name: 'PetData'}).schema = {type: 'number'};421            api.paths['/pets'][method].responses[201].schema = {type: 'number'};422            api.paths['/pets'][method].consumes = ['text/plain'];423            api.paths['/pets'][method].produces = ['text/plain'];424            helper.initTest(api, function(supertest) {425              supertest426                [method]('/api/pets')427                .set('Content-Type', 'text/plain')428                .send('42.999')429                .expect(201, '42.999')430                .expect('Location', '/api/pets/42.999')431                .end(helper.checkResults(done));432            });433          }434        );435        it('should support dates',436          function(done) {437            _.find(api.paths['/pets'][method].parameters, {name: 'PetData'}).schema = {type: 'string', format: 'date'};438            api.paths['/pets'][method].responses[201].schema = {type: 'string', format: 'date'};439            api.paths['/pets'][method].consumes = ['text/plain'];440            api.paths['/pets'][method].produces = ['text/plain'];441            helper.initTest(api, function(supertest) {442              supertest443                [method]('/api/pets')444                .set('Content-Type', 'text/plain')445                .send('2000-01-02')446                .expect(201, '2000-01-02')447                .expect('Location', '/api/pets/2000-01-02')448                .end(helper.checkResults(done));449            });450          }451        );452        it('should support date-times',453          function(done) {454            _.find(api.paths['/pets'][method].parameters, {name: 'PetData'}).schema = {type: 'string', format: 'date-time'};455            api.paths['/pets'][method].responses[201].schema = {type: 'string', format: 'date-time'};456            api.paths['/pets'][method].consumes = ['text/plain'];457            api.paths['/pets'][method].produces = ['text/plain'];458            helper.initTest(api, function(supertest) {459              supertest460                [method]('/api/pets')461                .set('Content-Type', 'text/plain')462                .send('2000-01-02T03:04:05.006Z')463                .expect(201, '2000-01-02T03:04:05.006Z')464                .expect('Location', '/api/pets/2000-01-02T03%3A04%3A05.006Z')465                .end(helper.checkResults(done));466            });467          }468        );469        it('should support Buffers (as a string)',470          function(done) {471            _.find(api.paths['/pets'][method].parameters, {name: 'PetData'}).schema = {type: 'string'};472            api.paths['/pets'][method].responses[201].schema = {type: 'string'};473            api.paths['/pets'][method].consumes = ['text/plain'];474            api.paths['/pets'][method].produces = ['text/plain'];475            helper.initTest(api, function(supertest) {476              supertest477                [method]('/api/pets')478                .set('Content-Type', 'text/plain')479                .send(new Buffer('hello world').toString())480                .expect(201, 'hello world')481                .expect('Location', '/api/pets/hello%20world')482                .end(helper.checkResults(done));483            });484          }485        );486        it('should support Buffers (as JSON)',487          function(done) {488            _.find(api.paths['/pets'][method].parameters, {name: 'PetData'}).schema = {};489            api.paths['/pets'][method].responses[201].schema = {};490            api.paths['/pets'][method].consumes = ['application/octet-stream'];491            api.paths['/pets'][method].produces = ['text/plain'];492            helper.initTest(api, function(supertest) {493              supertest494                [method]('/api/pets')495                .set('Content-Type', 'application/octet-stream')496                .send(new Buffer('hello world').toString())497                .expect(201, {498                  type: 'Buffer',499                  data: [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]500                })501                .end(helper.checkResults(done, function(res) {502                  // The "Location" header should be set to an auto-generated value,503                  // since a Buffer has no "name" field504                  expect(res.headers.location).to.match(/^\/api\/pets\/\d+$/);505                  done();506                }));507            });508          }509        );510        it('should support undefined values',511          function(done) {512            var petParam = _.find(api.paths['/pets'][method].parameters, {name: 'PetData'});513            petParam.schema = {};514            petParam.required = false;515            api.paths['/pets'][method].responses[201].schema = {};516            helper.initTest(api, function(supertest) {517              supertest518                [method]('/api/pets')519                .set('Content-Type', 'text/plain')520                .expect(201, '')521                .end(helper.checkResults(done, function(res) {522                  expect(res.headers.location).to.match(/^\/api\/pets\/\w+$/);523                  done();524                }));525            });526          }527        );528        it('should support multipart/form-data',529          function(done) {530            api.paths['/pets/{PetName}/photos'][method].responses[201].schema = {};531            helper.initTest(api, function(supertest) {532              supertest533                [method]('/api/pets/Fido/photos')534                .field('Label', 'Photo 1')535                .field('Description', 'A photo of Fido')536                .attach('Photo', files.paths.oneMB)537                .expect(201)538                .end(helper.checkResults(done, function(res) {539                  expect(res.headers.location).to.match(/^\/api\/pets\/Fido\/photos\/\d+$/);540                  expect(res.body).to.deep.equal({541                    ID: res.body.ID,542                    Label: 'Photo 1',543                    Description: 'A photo of Fido',544                    Photo: {545                      fieldname: 'Photo',546                      originalname: '1MB.jpg',547                      name: res.body.Photo.name,548                      encoding: '7bit',549                      mimetype: 'image/jpeg',550                      path: res.body.Photo.path,551                      extension: 'jpg',552                      size: 683709,553                      truncated: false,554                      buffer: null555                    }556                  });557                  done();558                }));559            });560          }561        );562        it('should support files',563          function(done) {564            api.paths['/pets/{PetName}/photos'][method].responses[201].schema = {type: 'file'};565            helper.initTest(api, function(supertest) {566              supertest567                [method]('/api/pets/Fido/photos')568                .field('Label', 'Photo 1')569                .field('Description', 'A photo of Fido')570                .attach('Photo', files.paths.oneMB)571                .expect(201)572                .end(helper.checkResults(done, function(res) {573                  expect(res.headers.location).to.match(/^\/api\/pets\/Fido\/photos\/\d+$/);574                  expect(res.body).to.be.an.instanceOf(Buffer);575                  expect(res.body.length).to.equal(683709);576                  done();577                }));578            });579          }580        );581      });582      describe('Determining resource names (by property names)', function() {583        it('should determine the resource name from "Name" properties in its schema',584          function(done) {585            helper.initTest(api, function(supertest) {586              supertest587                [method]('/api/pets')588                .send({Name: 'Fido', Type: 'dog'})589                .expect('Location', '/api/pets/Fido')590                .end(helper.checkResults(done, function() {591                  supertest592                    .get('/api/pets/Fido')593                    .expect(200, {Name: 'Fido', Type: 'dog'})594                    .end(helper.checkResults(done));595                }));596            });597          }598        );599        it('should determine the resource name from "Name" properties in its schema, even if they\'re not present in the data',600          function(done) {601            var schemaProps = _.find(api.paths['/pets'][method].parameters, {name: 'PetData'}).schema.properties;602            schemaProps.ID = {type: 'integer'};603            helper.initTest(api, function(supertest) {604              supertest605                [method]('/api/pets')606                .send({Name: 'Fido', Type: 'dog'})607                .end(helper.checkResults(done, function(res) {608                  // An "ID" property should have been generated and used for the "Location" header609                  expect(res.headers.location).to.match(/^\/api\/pets\/\d+$/);610                  // Extract the ID from the "Location" HTTP header611                  var petID = parseInt(res.headers.location.match(/\d+$/)[0]);612                  expect(petID).not.to.satisfy(isNaN);613                  expect(petID).to.satisfy(isFinite);614                  // Verify that the ID property was set on the object615                  supertest616                    .get(res.headers.location)617                    .expect(200, {ID: petID, Name: 'Fido', Type: 'dog'})618                    .end(helper.checkResults(done));619                }));620            });621          }622        );623        it('should determine the resource name from "Name" properties in its data, even if they\'re not in the schema',624          function(done) {625            helper.initTest(api, function(supertest) {626              supertest627                [method]('/api/pets')628                .send({ID: 12345, Name: 'Fido', Type: 'dog'})   // <--- "ID" is not in the schema. "Name" is.629                .expect('Location', '/api/pets/12345')          // <--- "ID" is used instead of "Name"630                .end(helper.checkResults(done, function() {631                  supertest632                    .get('/api/pets/12345')633                    .expect(200, {ID: 12345, Name: 'Fido', Type: 'dog'})634                    .end(helper.checkResults(done));635                }));636            });637          }638        );639        it('should use a "byte" property in the schema as the resource name',640          function(done) {641            var schemaProps = _.find(api.paths['/pets'][method].parameters, {name: 'PetData'}).schema.properties;642            schemaProps.ID = {type: 'string', format: 'byte'};643            helper.initTest(api, function(supertest) {644              supertest645                [method]('/api/pets')646                .send({Name: 'Fido', Type: 'dog'})647                .end(helper.checkResults(done, function(res) {648                  // An "ID" property should have been generated and used for the "Location" header649                  expect(res.headers.location).to.match(/^\/api\/pets\/\d{1,3}$/);650                  // Extract the ID from the "Location" HTTP header651                  var petID = parseInt(res.headers.location.match(/\d+$/)[0]);652                  expect(petID).not.to.satisfy(isNaN);653                  expect(petID).to.satisfy(isFinite);654                  // Verify that the ID property was set on the object655                  supertest656                    .get(res.headers.location)657                    .expect(200, {ID: petID, Name: 'Fido', Type: 'dog'})658                    .end(helper.checkResults(done));659                }));660            });661          }662        );663        it('should use a "boolean" property in the schema as the resource name',664          function(done) {665            var schemaProps = _.find(api.paths['/pets'][method].parameters, {name: 'PetData'}).schema.properties;666            schemaProps.ID = {type: 'boolean'};667            helper.initTest(api, function(supertest) {668              supertest669                [method]('/api/pets')670                .send({Name: 'Fido', Type: 'dog'})671                .end(helper.checkResults(done, function(res) {672                  // An "ID" property should have been generated and used for the "Location" header673                  expect(res.headers.location).to.match(/^\/api\/pets\/(true|false)$/);674                  // Extract the ID from the "Location" HTTP header675                  var petID = res.headers.location.match(/(true|false)$/)[0] === 'true';676                  // Verify that the ID property was set on the object677                  supertest678                    .get(res.headers.location)679                    .expect(200, {ID: petID, Name: 'Fido', Type: 'dog'})680                    .end(helper.checkResults(done));681                }));682            });683          }684        );685        it('should use a "boolean" property in the data as the resource name',686          function(done) {687            helper.initTest(api, function(supertest) {688              supertest689                [method]('/api/pets')690                .send({ID: false, Name: 'Fido', Type: 'dog'})691                .expect('Location', '/api/pets/false')692                .end(helper.checkResults(done, function() {693                  supertest694                    .get('/api/pets/false')695                    .expect(200, {ID: false, Name: 'Fido', Type: 'dog'})696                    .end(helper.checkResults(done));697                }));698            });699          }700        );701        it('should use a "date" property in the schema as the resource name',702          function(done) {703            var schemaProps = _.find(api.paths['/pets'][method].parameters, {name: 'PetData'}).schema.properties;704            schemaProps.Key = {705              type: 'string',706              format: 'date'707            };708            api.paths['/pets/{PetName}'].get.responses[200].schema.properties = schemaProps;709            helper.initTest(api, function(supertest) {710              supertest711                [method]('/api/pets')712                .send({Key: '2005-11-09', Name: 'Fido', Type: 'dog'})713                .expect('Location', '/api/pets/2005-11-09')714                .end(helper.checkResults(done, function(res) {715                  supertest716                    .get('/api/pets/2005-11-09')717                    .expect(200, {Key: '2005-11-09', Name: 'Fido', Type: 'dog'})718                    .end(helper.checkResults(done));719                }));720            });721          }722        );723        it('should use a "date-time" property in the schema as the resource name',724          function(done) {725            var schemaProps = _.find(api.paths['/pets'][method].parameters, {name: 'PetData'}).schema.properties;726            schemaProps.key = {727              type: 'string',728              format: 'date-time'729            };730            helper.initTest(api, function(supertest) {731              supertest732                [method]('/api/pets')733                .send({key: '2005-11-09T08:07:06.005Z', Name: 'Fido', Type: 'dog'})734                .expect('Location', '/api/pets/2005-11-09T08%3A07%3A06.005Z')735                .end(helper.checkResults(done, function(res) {736                  supertest737                    .get('/api/pets/2005-11-09T08%3A07%3A06.005Z')738                    .expect(200, {key: '2005-11-09T08:07:06.005Z', Name: 'Fido', Type: 'dog'})739                    .end(helper.checkResults(done));740                }));741            });742          }743        );744        it('should use a Date property in the data as the resource name',745          function(done) {746            helper.initTest(api, function(supertest) {747              supertest748                [method]('/api/pets')749                .send({code: new Date(Date.UTC(2000, 1, 2, 3, 4, 5, 6)), Name: 'Fido', Type: 'dog'})750                .expect('Location', '/api/pets/2000-02-02T03%3A04%3A05.006Z')751                .end(helper.checkResults(done, function() {752                  supertest753                    .get('/api/pets/2000-02-02T03%3A04%3A05.006Z')754                    .expect(200, {code: '2000-02-02T03:04:05.006Z', Name: 'Fido', Type: 'dog'})755                    .end(helper.checkResults(done));756                }));757            });758          }759        );760        it('should use a Date property that was added by other middleware as the resource name',761          function(done) {762            function messWithTheBody(req, res, next) {763              if (req.method === method.toUpperCase()) {764                req.body.Id = new Date(Date.UTC(2000, 1, 2, 3, 4, 5, 6));765              }766              next();767            }768            helper.initTest(messWithTheBody, api, function(supertest) {769              supertest770                [method]('/api/pets')771                .send({Name: 'Fido', Type: 'dog'})772                .expect('Location', '/api/pets/2000-02-02T03%3A04%3A05.006Z')773                .end(helper.checkResults(done, function(res) {774                  supertest775                    .get('/api/pets/2000-02-02T03%3A04%3A05.006Z')776                    .expect(200, {Name: 'Fido', Type: 'dog', Id: '2000-02-02T03:04:05.006Z'})777                    .end(helper.checkResults(done));778                }));779            });780          }781        );782        it('should NOT use object or array properties as the resource name',783          function(done) {784            var petParam = _.find(api.paths['/pets'][method].parameters, {name: 'PetData'});785            petParam.schema.properties.Name.type = 'object';786            petParam.schema.required = ['Name'];787            api.paths['/pets'].get.responses[200].schema.items = petParam.schema;788            helper.initTest(api, function(supertest) {789              supertest790                [method]('/api/pets')791                .send({ID: [1, 2, 3], Name: {fido: true}, Type: 'dog'})   // <-- Neither "ID" nor "Name" is a valid resource name792                .end(helper.checkResults(done, function(res) {793                  // A resource name was auto-generated, since ID and Name weren't valid794                  expect(res.headers.location).to.match(/^\/api\/pets\/\d+$/);795                  // Verify that the object remained unchanged796                  supertest797                    .get('/api/pets')798                    .expect(200, [{ID: [1, 2, 3], Name: {fido: true}, Type: 'dog'}])799                    .end(helper.checkResults(done));800                }));801            });802          }803        );804      });805      describe('Determining resource names (by required properties)', function() {806        it('should use the first required property as the resource name',807          function(done) {808            _.remove(api.paths['/pets/{PetName}/photos'][method].parameters, {name: 'ID'});809            _.find(api.paths['/pets/{PetName}/photos/{ID}'].parameters, {name: 'ID'}).type = 'string';810            helper.initTest(api, function(supertest) {811              supertest812                [method]('/api/pets/Fido/photos')813                .field('Label', 'Photo 1')814                .attach('Photo', files.paths.oneMB)815                .expect('Location', '/api/pets/Fido/photos/Photo%201')816                .end(helper.checkResults(done, function(res) {817                  supertest818                    .get('/api/pets/Fido/photos/Photo%201')819                    .expect(200)820                    .end(helper.checkResults(done, function(res) {821                      expect(res.body).to.be.an.instanceOf(Buffer);822                      expect(res.body.length).to.equal(683709);823                      done();824                    }));825                }));826            });827          }828        );829        it('should NOT use object or array properties as the resource name',830          function(done) {831            _.remove(api.paths['/pets/{PetName}/photos'][method].parameters, {name: 'ID'});832            _.find(api.paths['/pets/{PetName}/photos/{ID}'].parameters, {name: 'ID'}).type = 'string';833            var labelParam = _.find(api.paths['/pets/{PetName}/photos'][method].parameters, {name: 'Label'});834            labelParam.type = 'array';835            labelParam.items = {836              type: 'string'837            };838            helper.initTest(api, function(supertest) {839              supertest840                [method]('/api/pets/Fido/photos')841                .field('Label', 'a, b, c')842                .attach('Photo', files.paths.oneMB)843                .expect('Location', '/api/pets/Fido/photos/1MB.jpg')844                .end(helper.checkResults(done, function(res) {845                  supertest846                    .get('/api/pets/Fido/photos/1MB.jpg')847                    .expect(200)848                    .end(helper.checkResults(done, function(res) {849                      expect(res.body).to.be.an.instanceOf(Buffer);850                      expect(res.body.length).to.equal(683709);851                      done();852                    }));853                }));854            });855          }856        );857      });858      describe('Determining resource names (by file name)', function() {859        it('should use the client-side file name as the resource name',860          function(done) {861            _.remove(api.paths['/pets/{PetName}/photos'][method].parameters, {name: 'ID'});862            _.find(api.paths['/pets/{PetName}/photos'][method].parameters, {name: 'Label'}).required = false;863            _.find(api.paths['/pets/{PetName}/photos/{ID}'].parameters, {name: 'ID'}).type = 'string';864            helper.initTest(api, function(supertest) {865              supertest866                [method]('/api/pets/Fido/photos')867                .field('Label', 'Photo 1')868                .attach('Photo', files.paths.oneMB)869                .expect('Location', '/api/pets/Fido/photos/1MB.jpg')870                .end(helper.checkResults(done, function(res) {871                  supertest872                    .get('/api/pets/Fido/photos/1MB.jpg')873                    .expect(200)874                    .end(helper.checkResults(done, function(res) {875                      expect(res.body).to.be.an.instanceOf(Buffer);876                      expect(res.body.length).to.equal(683709);877                      done();878                    }));879                }));880            });881          }882        );883        it('should use the server-side file name as the resource name',884          function(done) {885            _.remove(api.paths['/pets/{PetName}/photos'][method].parameters, {name: 'ID'});886            _.find(api.paths['/pets/{PetName}/photos'][method].parameters, {name: 'Label'}).required = false;887            _.find(api.paths['/pets/{PetName}/photos/{ID}'].parameters, {name: 'ID'}).type = 'string';888            function messWithTheBody(req, res, next) {889              if (req.method === method.toUpperCase()) {890                // Mimic the filename not being included in the Content-Disposition header891                req.files.Photo.originalname = null;892              }893              next();894            }895            helper.initTest(messWithTheBody, api, function(supertest) {896              supertest897                [method]('/api/pets/Fido/photos')898                .field('Label', 'Photo 1')899                .attach('Photo', files.paths.oneMB)900                .end(helper.checkResults(done, function(res) {901                  expect(res.headers.location).not.to.equal('/api/pets/Fido/photos/1MB.jpg');902                  expect(res.headers.location).to.match(/^\/api\/pets\/Fido\/photos\/\w+\.jpg$/);903                  supertest904                    .get(res.headers.location)905                    .expect(200)906                    .end(helper.checkResults(done, function(res) {907                      expect(res.body).to.be.an.instanceOf(Buffer);908                      expect(res.body.length).to.equal(683709);909                      done();910                    }));911                }));912            });913          }914        );915        it('should use an auto-generated resource name if no file was uploaded',916          function(done) {917            var params = api.paths['/pets/{PetName}/photos'][method].parameters;918            _.remove(api.paths['/pets/{PetName}/photos'][method].parameters, {name: 'ID'});919            _.find(params, {name: 'Label'}).required = false;920            _.find(params, {name: 'Photo'}).required = false;921            helper.initTest(api, function(supertest) {922              supertest923                [method]('/api/pets/Fido/photos')924                .field('Label', 'Photo 1')925                .end(helper.checkResults(done, function(res) {926                  // A resource name was auto-generated, since no file was uploaded927                  expect(res.headers.location).to.match(/^\/api\/pets\/Fido\/photos\/\d+$/);928                  supertest929                    .get(res.headers.location)930                    .expect(410)931                    .end(done);932                }));933            });934          }935        );936        it('should use an auto-generated resource name if the body is empty',937          function(done) {938            var params = api.paths['/pets/{PetName}/photos'][method].parameters;939            _.remove(api.paths['/pets/{PetName}/photos'][method].parameters, {name: 'ID'});940            _.find(params, {name: 'Label'}).required = false;941            _.find(params, {name: 'Photo'}).required = false;942            api.paths['/pets/{PetName}/photos'][method].consumes = ['text/plain', 'multipart/form-data'];943            helper.initTest(api, function(supertest) {944              supertest945                [method]('/api/pets/Fido/photos')946                .set('Content-Type', 'text/plain')947                .end(helper.checkResults(done, function(res) {948                  // A resource name was auto-generated, since no file was uploaded949                  expect(res.headers.location).to.match(/^\/api\/pets\/Fido\/photos\/\d+$/);950                  supertest951                    .get(res.headers.location)952                    .expect(410)953                    .end(done);954                }));955            });956          }957        );958        it('should use an auto-generated resource name if there is more than one file param',959          function(done) {960            var params = api.paths['/pets/{PetName}/photos'][method].parameters;961            _.remove(params, {name: 'ID'});962            _.find(params, {name: 'Label'}).required = false;963            _.find(params, {name: 'Photo'}).required = false;964            params.push({965              name: 'Photo2',966              in: 'formData',967              type: 'file'968            });969            helper.initTest(api, function(supertest) {970              supertest971                [method]('/api/pets/Fido/photos')972                .field('Label', 'Photo 1')973                .attach('Photo2', files.paths.oneMB)       // <--- Only sending one file.  But there are 2 file params974                .end(helper.checkResults(done, function(res) {975                  // A resource name was auto-generated, since there are multiple file params976                  expect(res.headers.location).to.match(/^\/api\/pets\/Fido\/photos\/\d+$/);977                  supertest978                    .get(res.headers.location)979                    .expect(200)980                    .end(helper.checkResults(done, function(res) {981                      expect(res.body).to.be.an.instanceOf(Buffer);982                      expect(res.body.length).to.equal(683709);983                      done();984                    }));985                }));986            });987          }988        );989      });990      describe('Auto-generated resource names', function() {991        it('should generate a unique ID if no "Name" property can be determined',992          function(done) {993            // The schema is an empty object (no "name" properties)994            _.find(api.paths['/pets'][method].parameters, {name: 'PetData'}).schema = {};995            api.paths['/pets'][method].responses[201].schema = {};996            helper.initTest(api, function(supertest) {997              supertest998                [method]('/api/pets')999                .send({age: 42, dob: new Date(Date.UTC(2000, 1, 2, 3, 4, 5, 6))})  // <--- No "name" properties1000                .expect(201, {age: 42, dob: '2000-02-02T03:04:05.006Z'})1001                .end(helper.checkResults(done, function(res) {1002                  // The "Location" header should be set to an auto-generated value1003                  expect(res.headers.location).to.match(/^\/api\/pets\/\d+$/);1004                  done();1005                }));1006            });1007          }1008        );1009        it('should generate a string value for the resource\'s "Name" property, if not set',1010          function(done) {1011            // Make "Name" property optional1012            var petParam = _.find(api.paths['/pets'][method].parameters, {name: 'PetData'});1013            petParam.schema.required = [];1014            helper.initTest(api, function(supertest) {1015              supertest1016                [method]('/api/pets')1017                .send({Type: 'dog', Age: 4})    // <--- The "Name" property isn't set1018                .end(helper.checkResults(done, function(res) {1019                  // A "Name" should have been generated, and used as the resource's URL1020                  expect(res.headers.location).to.match(/^\/api\/pets\/\w+$/);1021                  // Extract the pet's Name from the "Location" header1022                  var petName = res.headers.location.match(/([^\/]+)$/)[0];1023                  supertest1024                    .get(res.headers.location)1025                    .expect(200)1026                    .end(helper.checkResults(done, function(res) {1027                      expect(res.body).to.deep.equal({1028                        Type: 'dog',1029                        Age: 4,1030                        Name: petName1031                      });1032                      done();1033                    }));1034                }));1035            });1036          }1037        );1038        it('should generate a string value for the resource\'s "Name" property, even if the body is empty',1039          function(done) {1040            // Make all data optional1041            var petParam = _.find(api.paths['/pets'][method].parameters, {name: 'PetData'});1042            petParam.required = false;1043            helper.initTest(api, function(supertest) {1044              supertest1045                [method]('/api/pets')      // <--- No data was sent at all1046                .end(helper.checkResults(done, function(res) {1047                  // A "Name" should have been generated, and used as the resource's URL1048                  expect(res.headers.location).to.match(/^\/api\/pets\/\w+$/);1049                  // Extract the pet's Name from the "Location" header1050                  var petName = res.headers.location.match(/([^\/]+)$/)[0];1051                  supertest1052                    .get(res.headers.location)1053                    .expect(200)1054                    .end(helper.checkResults(done, function(res) {1055                      expect(res.body).to.deep.equal({1056                        Name: petName   // <--- A "Name" property was generated and added to an empty object1057                      });1058                      done();1059                    }));1060                }));1061            });1062          }1063        );1064        it('should generate an integer value for the resource\'s "Name" property, if not set',1065          function(done) {1066            // Make the "Name" property optional, and an integer1067            var petParam = _.find(api.paths['/pets'][method].parameters, {name: 'PetData'});1068            petParam.schema.required = [];1069            petParam.schema.properties.Name.type = 'integer';1070            api.paths['/pets/{PetName}'].get.responses[200].schema = petParam.schema;1071            helper.initTest(api, function(supertest) {1072              supertest1073                [method]('/api/pets')1074                .send({Type: 'dog', Age: 4})    // <--- The "Name" property isn't set1075                .end(helper.checkResults(done, function(res) {1076                  // A "Name" should have been generated, and used as the resource's URL1077                  expect(res.headers.location).to.match(/^\/api\/pets\/\d+$/);1078                  // Extract the pet's Name from the "Location" header1079                  var petNameAsString = res.headers.location.match(/([^\/]+)$/)[0];1080                  var petNameAsInteger = parseInt(petNameAsString);1081                  expect(petNameAsInteger).not.to.satisfy(isNaN);1082                  expect(petNameAsInteger).to.satisfy(isFinite);1083                  supertest1084                    .get(res.headers.location)1085                    .expect(200)1086                    .end(helper.checkResults(done, function(res) {1087                      expect(res.body).to.deep.equal({1088                        Type: 'dog',1089                        Age: 4,1090                        Name: petNameAsInteger1091                      });1092                      done();1093                    }));1094                }));1095            });1096          }1097        );1098        it('should generate a date value for the resource\'s "Name" property, if not set',1099          function(done) {1100            // Make the "Name" property optional, and an integer1101            var petParam = _.find(api.paths['/pets'][method].parameters, {name: 'PetData'});1102            petParam.schema.required = [];1103            petParam.schema.properties.Name.type = 'string';1104            petParam.schema.properties.Name.format = 'date';1105            api.paths['/pets/{PetName}'].get.responses[200].schema = petParam.schema;1106            helper.initTest(api, function(supertest) {1107              supertest1108                [method]('/api/pets')1109                .send({Type: 'dog', Age: 4})    // <--- The "Name" property isn't set1110                .end(helper.checkResults(done, function(res) {1111                  // A "Name" should have been generated, and used as the resource's URL1112                  expect(res.headers.location).to.match(/^\/api\/pets\/\d{4}-\d\d-\d\d$/);1113                  // Extract the pet's Name from the "Location" header1114                  var petNameAsString = res.headers.location.match(/([^\/]+)$/)[0];1115                  var petNameAsDate = new Date(petNameAsString);1116                  expect(petNameAsDate.valueOf()).not.to.satisfy(isNaN);1117                  expect(petNameAsDate.valueOf()).to.satisfy(isFinite);1118                  supertest1119                    .get(res.headers.location)1120                    .expect(200)1121                    .end(helper.checkResults(done, function(res) {1122                      expect(res.body).to.deep.equal({1123                        Type: 'dog',1124                        Age: 4,1125                        Name: petNameAsString1126                      });1127                      done();1128                    }));1129                }));1130            });1131          }1132        );1133        it('should generate a date-time value for the resource\'s "Name" property, if not set',1134          function(done) {1135            // Make the "Name" property optional, and an integer1136            var petParam = _.find(api.paths['/pets'][method].parameters, {name: 'PetData'});1137            petParam.schema.required = [];1138            petParam.schema.properties.Name.type = 'string';1139            petParam.schema.properties.Name.format = 'date-time';1140            api.paths['/pets/{PetName}'].get.responses[200].schema = petParam.schema;1141            helper.initTest(api, function(supertest) {1142              supertest1143                [method]('/api/pets')1144                .send({Type: 'dog', Age: 4})    // <--- The "Name" property isn't set1145                .end(helper.checkResults(done, function(res) {1146                  // A "Name" should have been generated, and used as the resource's URL1147                  expect(res.headers.location).to.match(/^\/api\/pets\/\d{4}-\d\d-\d\dT\d\d\%3A\d\d\%3A\d\d\.\d\d\dZ$/);1148                  // Extract the pet's Name from the "Location" header1149                  var petNameAsString = decodeURIComponent(res.headers.location.match(/([^\/]+)$/)[0]);1150                  var petNameAsDate = new Date(petNameAsString);1151                  expect(petNameAsDate.valueOf()).not.to.satisfy(isNaN);1152                  expect(petNameAsDate.valueOf()).to.satisfy(isFinite);1153                  supertest1154                    .get(res.headers.location)1155                    .expect(200)1156                    .end(helper.checkResults(done, function(res) {1157                      expect(res.body).to.deep.equal({1158                        Type: 'dog',1159                        Age: 4,1160                        Name: petNameAsString1161                      });1162                      done();1163                    }));1164                }));1165            });1166          }1167        );1168        it('should NOT generate an array value for the resource\'s "Name" property, if not set',1169          function(done) {1170            // Make the "Name" property optional, and an integer1171            var petParam = _.find(api.paths['/pets'][method].parameters, {name: 'PetData'});1172            petParam.schema.required = [];1173            petParam.schema.properties.Name.type = 'array';1174            petParam.schema.properties.Name.items = {type: 'string'};1175            helper.initTest(api, function(supertest) {1176              supertest1177                [method]('/api/pets')1178                .send({Type: 'dog', Age: 4})    // <--- The "Name" property isn't set1179                .end(helper.checkResults(done, function(res) {1180                  // A "Name" property should have been auto-generated, but it should NOT be an array1181                  expect(res.headers.location).to.match(/^\/api\/pets\/\d+$/);1182                  done();1183                }));1184            });1185          }1186        );1187      });1188    });1189  });...

Full Screen

Full Screen

delete-collection.spec.js

Source:delete-collection.spec.js Github

copy

Full Screen

1var swagger    = require('../../../'),2    expect     = require('chai').expect,3    _          = require('lodash'),4    files      = require('../../fixtures/files'),5    helper     = require('./helper');6describe('Query Collection Mock', function() {7  describe('DELETE', function() {8    'use strict';9    var api;10    beforeEach(function() {11      api = _.cloneDeep(files.parsed.petStore);12      api.paths['/pets'].delete = _.cloneDeep(api.paths['/pets'].get);13      api.paths['/pets/{PetName}/photos'].delete = _.cloneDeep(api.paths['/pets/{PetName}/photos'].get);14    });15    it('should delete all resources in the collection',16      function(done) {17        var dataStore = new swagger.MemoryDataStore();18        var resources = [19          new swagger.Resource('/api/pets/Fido', {Name: 'Fido', Type: 'dog'}),20          new swagger.Resource('/api/pets/Fluffy', {Name: 'Fluffy', Type: 'cat'}),21          new swagger.Resource('/api/pets/Polly', {Name: 'Polly', Type: 'bird'})22        ];23        dataStore.save(resources, function() {24          helper.initTest(dataStore, api, function(supertest) {25            supertest26              .delete('/api/pets')27              .expect(200)28              .end(helper.checkResults(done, function() {29                // Verify that all resources were deleted30                dataStore.getCollection('/api/pets', function(err, resources) {31                  if (err) {32                    return done(err);33                  }34                  expect(resources).to.have.lengthOf(0);35                  done();36                });37              }));38          });39        });40      }41    );42    it('should delete an empty collection',43      function(done) {44        helper.initTest(api, function(supertest) {45          supertest46            .delete('/api/pets')47            .expect(200)48            .end(helper.checkResults(done));49        });50      }51    );52    it('should return the deleted resources if the Swagger API schema is an array',53      function(done) {54        var dataStore = new swagger.MemoryDataStore();55        var resources = [56          new swagger.Resource('/api/pets/Fido', {Name: 'Fido', Type: 'dog'}),57          new swagger.Resource('/api/pets/Fluffy', {Name: 'Fluffy', Type: 'cat'}),58          new swagger.Resource('/api/pets/Polly', {Name: 'Polly', Type: 'bird'})59        ];60        dataStore.save(resources, function() {61          helper.initTest(dataStore, api, function(supertest) {62            supertest63              .delete('/api/pets')64              .expect(200, [65                {Name: 'Fido', Type: 'dog'},66                {Name: 'Fluffy', Type: 'cat'},67                {Name: 'Polly', Type: 'bird'}68              ])69              .end(helper.checkResults(done));70          });71        });72      }73    );74    it('should return the first deleted resource if the Swagger API schema is an object',75      function(done) {76        api.paths['/pets'].delete.responses[200].schema = {};77        var dataStore = new swagger.MemoryDataStore();78        var resources = [79          new swagger.Resource('/api/pets/Fido', {Name: 'Fido', Type: 'dog'}),80          new swagger.Resource('/api/pets/Fluffy', {Name: 'Fluffy', Type: 'cat'}),81          new swagger.Resource('/api/pets/Polly', {Name: 'Polly', Type: 'bird'})82        ];83        dataStore.save(resources, function() {84          helper.initTest(dataStore, api, function(supertest) {85            supertest86              .delete('/api/pets')87              .expect(200, {Name: 'Fido', Type: 'dog'})88              .end(helper.checkResults(done, function() {89                // Verify that all resources were deleted90                dataStore.getCollection('/api/pets', function(err, resources) {91                  if (err) {92                    return done(err);93                  }94                  expect(resources).to.have.lengthOf(0);95                  done();96                });97              }));98          });99        });100      }101    );102    it('should return the deleted resources if the Swagger API schema is a wrapped array',103      function(done) {104        // Wrap the "pet" definition in an envelope object105        api.paths['/pets'].delete.responses[200].schema = {106          properties: {107            code: {type: 'integer', default: 42},108            message: {type: 'string', default: 'hello world'},109            error: {type: 'object'},110            result: {type: 'array', items: _.cloneDeep(api.definitions.pet)}111          }112        };113        var dataStore = new swagger.MemoryDataStore();114        var resources = [115          new swagger.Resource('/api/pets/Fido', {Name: 'Fido', Type: 'dog'}),116          new swagger.Resource('/api/pets/Fluffy', {Name: 'Fluffy', Type: 'cat'}),117          new swagger.Resource('/api/pets/Polly', {Name: 'Polly', Type: 'bird'})118        ];119        dataStore.save(resources, function() {120          helper.initTest(dataStore, api, function(supertest) {121            supertest122              .delete('/api/pets')123              .expect(200, {124                code: 42,125                message: 'hello world',126                result: [127                  {Name: 'Fido', Type: 'dog'},128                  {Name: 'Fluffy', Type: 'cat'},129                  {Name: 'Polly', Type: 'bird'}130                ]131              })132              .end(helper.checkResults(done));133          });134        });135      }136    );137    it('should return the first deleted resource if the Swagger API schema is a wrapped object',138      function(done) {139        // Wrap the "pet" definition in an envelope object140        api.paths['/pets'].delete.responses[200].schema = {141          properties: {142            code: {type: 'integer', default: 42},143            message: {type: 'string', default: 'hello world'},144            error: {type: 'object'},145            result: _.cloneDeep(api.definitions.pet)146          }147        };148        var dataStore = new swagger.MemoryDataStore();149        var resources = [150          new swagger.Resource('/api/pets/Fido', {Name: 'Fido', Type: 'dog'}),151          new swagger.Resource('/api/pets/Fluffy', {Name: 'Fluffy', Type: 'cat'}),152          new swagger.Resource('/api/pets/Polly', {Name: 'Polly', Type: 'bird'})153        ];154        dataStore.save(resources, function() {155          helper.initTest(dataStore, api, function(supertest) {156            supertest157              .delete('/api/pets')158              .expect(200, {code: 42, message: 'hello world', result: {Name: 'Fido', Type: 'dog'}})159              .end(helper.checkResults(done, function() {160                // Verify that all resources were deleted161                dataStore.getCollection('/api/pets', function(err, resources) {162                  if (err) {163                    return done(err);164                  }165                  expect(resources).to.have.lengthOf(0);166                  done();167                });168              }));169          });170        });171      }172    );173    it('should not return the deleted resources on a 204 response, even if the Swagger API schema is an array',174      function(done) {175        api.paths['/pets'].delete.responses[204] = api.paths['/pets'].delete.responses[200];176        delete api.paths['/pets'].delete.responses[200];177        var dataStore = new swagger.MemoryDataStore();178        var resources = [179          new swagger.Resource('/api/pets/Fido', {Name: 'Fido', Type: 'dog'}),180          new swagger.Resource('/api/pets/Fluffy', {Name: 'Fluffy', Type: 'cat'}),181          new swagger.Resource('/api/pets/Polly', {Name: 'Polly', Type: 'bird'})182        ];183        dataStore.save(resources, function() {184          helper.initTest(dataStore, api, function(supertest) {185            supertest186              .delete('/api/pets')187              .expect(204, '')188              .end(helper.checkResults(done, function() {189                // Verify that all resources were deleted190                dataStore.getCollection('/api/pets', function(err, resources) {191                  if (err) {192                    return done(err);193                  }194                  expect(resources).to.have.lengthOf(0);195                  done();196                });197              }));198          });199        });200      }201    );202    it('should return an empty array if nothing was deleted',203      function(done) {204        helper.initTest(api, function(supertest) {205          supertest206            .delete('/api/pets')207            .expect(200, [])208            .end(helper.checkResults(done));209        });210      }211    );212    it('should return nothing if nothing was deleted and the Swagger API schema is an object',213      function(done) {214        api.paths['/pets'].delete.responses[200].schema = {};215        helper.initTest(api, function(supertest) {216          supertest217            .delete('/api/pets')218            .expect(200, '')219            .end(helper.checkResults(done));220        });221      }222    );223    it('should return `res.body` if already set by other middleware',224      function(done) {225        function messWithTheBody(req, res, next) {226          res.body = {message: 'Not the response you expected'};227          next();228        }229        helper.initTest(messWithTheBody, api, function(supertest) {230          supertest231            .delete('/api/pets')232            .expect(200, {message: 'Not the response you expected'})233            .end(helper.checkResults(done));234        });235      }236    );237    it('should return a 500 error if a DataStore open error occurs',238      function(done) {239        var dataStore = new swagger.MemoryDataStore();240        dataStore.__openDataStore = function(collection, callback) {241          setImmediate(callback, new Error('Test Error'));242        };243        helper.initTest(dataStore, api, function(supertest) {244          supertest245            .delete('/api/pets')246            .expect(500)247            .end(function(err, res) {248              if (err) {249                return done(err);250              }251              expect(res.text).to.contain('Error: Test Error');252              done();253            });254        });255      }256    );257    it('should return a 500 error if a DataStore update error occurs',258      function(done) {259        var dataStore = new swagger.MemoryDataStore();260        dataStore.__saveDataStore = function(collection, data, callback) {261          setImmediate(callback, new Error('Test Error'));262        };263        var resource = new swagger.Resource('/api/pets/Fido', {Name: 'Fido', Type: 'dog'});264        dataStore.save(resource, function() {265          helper.initTest(dataStore, api, function(supertest) {266            supertest267              .delete('/api/pets')268              .expect(500)269              .end(function(err, res) {270                if (err) {271                  return done(err);272                }273                expect(res.text).to.contain('Error: Test Error');274                done();275              });276          });277        });278      }279    );280    describe('different data types', function() {281      it('should delete a string',282        function(done) {283          // Create a 200 response to return a string284          api.paths['/pets'].delete.responses['200'] = {285            description: '200 response',286            schema: {287              type: 'array',288              items: {289                type: 'string'290              }291            }292          };293          // Create a string resource294          var dataStore = new swagger.MemoryDataStore();295          var resource = new swagger.Resource('/api/pets/Fido', 'I am Fido');296          dataStore.save(resource, function() {297            helper.initTest(dataStore, api, function(supertest) {298              // Delete the string resource299              supertest300                .delete('/api/pets')301                .expect('Content-Type', 'application/json; charset=utf-8')302                .expect(200, ['I am Fido'])303                .end(helper.checkResults(done));304            });305          });306        }307      );308      it('should delete an empty string',309        function(done) {310          // Create a 200 response to return a string311          api.paths['/pets'].delete.responses['200'] = {312            description: '200 response',313            schema: {314              type: 'array',315              items: {316                type: 'string'317              }318            }319          };320          // Create an empty string resource321          var dataStore = new swagger.MemoryDataStore();322          var resource = new swagger.Resource('/api/pets/Fido', '');323          dataStore.save(resource, function() {324            helper.initTest(dataStore, api, function(supertest) {325              // Delete the string resource326              supertest327                .delete('/api/pets')328                .expect('Content-Type', 'application/json; charset=utf-8')329                .expect(200, [''])330                .end(helper.checkResults(done));331            });332          });333        }334      );335      it('should delete a number',336        function(done) {337          // Create a 200 response to return a number338          api.paths['/pets'].delete.responses['200'] = {339            description: '200 response',340            schema: {341              type: 'array',342              items: {343                type: 'number'344              }345            }346          };347          // Create a number resource348          var dataStore = new swagger.MemoryDataStore();349          var resource = new swagger.Resource('/api/pets/Fido', 42.999);350          dataStore.save(resource, function() {351            helper.initTest(dataStore, api, function(supertest) {352              // Delete the number resource353              supertest354                .delete('/api/pets')355                .expect('Content-Type', 'application/json; charset=utf-8')356                .expect(200, [42.999])357                .end(helper.checkResults(done));358            });359          });360        }361      );362      it('should delete a date',363        function(done) {364          // Create a 200 response to return a date365          api.paths['/pets'].delete.responses['200'] = {366            description: '200 response',367            schema: {368              type: 'array',369              items: {370                type: 'string',371                format: 'date'372              }373            }374          };375          // Create a date resource376          var dataStore = new swagger.MemoryDataStore();377          var resource = new swagger.Resource('/api/pets/Fido', new Date(Date.UTC(2000, 1, 2, 3, 4, 5, 6)));378          dataStore.save(resource, function() {379            helper.initTest(dataStore, api, function(supertest) {380              // Delete the date resource381              supertest382                .delete('/api/pets')383                .expect('Content-Type', 'application/json; charset=utf-8')384                .expect(200, ['2000-02-02'])385                .end(helper.checkResults(done));386            });387          });388        }389      );390      it('should delete a Buffer (as a string)',391        function(done) {392          // Create a 200 response to return a Buffer393          api.paths['/pets'].delete.responses['200'] = {394            description: '200 response',395            schema: {396              type: 'array',397              items: {398                type: 'string'399              }400            }401          };402          // Create a Buffer resource403          var dataStore = new swagger.MemoryDataStore();404          var resource = new swagger.Resource('/api/pets/Fido', new Buffer('hello world'));405          dataStore.save(resource, function() {406            helper.initTest(dataStore, api, function(supertest) {407              // Delete the Buffer resource408              supertest409                .delete('/api/pets')410                .expect('Content-Type', 'application/json; charset=utf-8')411                .expect(200, ['hello world'])412                .end(helper.checkResults(done));413            });414          });415        }416      );417      it('should delete a Buffer (as JSON)',418        function(done) {419          // Create a 200 response to return a Buffer420          api.paths['/pets'].delete.responses['200'] = {421            description: '200 response',422            schema: {423              type: 'array',424              items: {}425            }426          };427          // Create a Buffer resource428          var dataStore = new swagger.MemoryDataStore();429          var resource = new swagger.Resource('/api/pets/Fido', new Buffer('hello world'));430          dataStore.save(resource, function() {431            helper.initTest(dataStore, api, function(supertest) {432              // Delete the Buffer resource433              supertest434                .delete('/api/pets')435                .expect('Content-Type', 'application/json; charset=utf-8')436                .expect(200, [437                  {438                    type: 'Buffer',439                    data: [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]440                  }441                ])442                .end(helper.checkResults(done));443            });444          });445        }446      );447      it('should delete an undefined value',448        function(done) {449          // Create a 200 response to return an object450          api.paths['/pets'].delete.responses['200'] = {451            description: '200 response',452            schema: {453              type: 'array',454              items: {}455            }456          };457          // Create a resource with no value458          var dataStore = new swagger.MemoryDataStore();459          var resource = new swagger.Resource('/api/pets/Fido');460          dataStore.save(resource, function() {461            helper.initTest(dataStore, api, function(supertest) {462              // Delete the undefined resource463              supertest464                .delete('/api/pets')465                .expect('Content-Type', 'application/json; charset=utf-8')466                .expect(200, [null])    // <--- [undefined] is serialized as [null] in JSON467                .end(helper.checkResults(done));468            });469          });470        }471      );472      it('should delete a null value',473        function(done) {474          // Create a 200 response to return an object475          api.paths['/pets'].delete.responses['200'] = {476            description: '200 response',477            schema: {478              type: 'array',479              items: {}480            }481          };482          // Create a resource with a null value483          var dataStore = new swagger.MemoryDataStore();484          var resource = new swagger.Resource('/api/pets/Fido', null);485          dataStore.save(resource, function() {486            helper.initTest(dataStore, api, function(supertest) {487              // Delete the null resource488              supertest489                .delete('/api/pets')490                .expect('Content-Type', 'application/json; charset=utf-8')491                .expect(200, [null])492                .end(helper.checkResults(done));493            });494          });495        }496      );497      it('should delete multipart/form-data',498        function(done) {499          // Create a 200 response to return an object500          api.paths['/pets/{PetName}/photos'].delete.responses[200] = {501            description: '200 response',502            schema: {503              type: 'array',504              items: {}505            }506          };507          helper.initTest(api, function(supertest) {508            // Save a pet photo (multipart/form-data)509            supertest510              .post('/api/pets/Fido/photos')511              .field('Label', 'Photo 1')512              .field('Description', 'A photo of Fido')513              .attach('Photo', files.paths.oneMB)514              .expect(201)515              .end(helper.checkResults(done, function() {516                // Delete the photo517                supertest518                  .delete('/api/pets/Fido/photos')519                  .expect('Content-Type', 'application/json; charset=utf-8')520                  .expect(200)521                  .end(helper.checkResults(done, function(res2) {522                    expect(res2.body).to.deep.equal([523                      {524                        ID: res2.body[0].ID,525                        Label: 'Photo 1',526                        Description: 'A photo of Fido',527                        Photo: {528                          fieldname: 'Photo',529                          originalname: '1MB.jpg',530                          name: res2.body[0].Photo.name,531                          encoding: '7bit',532                          mimetype: 'image/jpeg',533                          path: res2.body[0].Photo.path,534                          extension: 'jpg',535                          size: 683709,536                          truncated: false,537                          buffer: null538                        }539                      }540                    ]);541                    done();542                  }));543              }));544          });545        }546      );547      it('should delete a file',548        function(done) {549          // Create a 200 response to return a file550          api.paths['/pets/{PetName}/photos'].delete.responses[200] = {551            description: '200 response',552            schema: {553              type: 'array',554              items: {555                type: 'file'556              }557            }558          };559          helper.initTest(api, function(supertest) {560            // Save a pet photo (multipart/form-data)561            supertest562              .post('/api/pets/Fido/photos')563              .field('Label', 'Photo 1')564              .field('Description', 'A photo of Fido')565              .attach('Photo', files.paths.oneMB)566              .expect(201)567              .end(helper.checkResults(done, function() {568                // Delete the photo569                supertest570                  .delete('/api/pets/Fido/photos')571                  .expect('Content-Type', 'application/json; charset=utf-8')572                  .expect(200)573                  .end(helper.checkResults(done, function(res2) {574                    // It should NOT be an attachment575                    expect(res2.headers['content-disposition']).to.be.undefined;576                    // There's no such thing as an "array of files",577                    // so we send back an array of file info578                    expect(res2.body).to.deep.equal([579                      {580                        fieldname: 'Photo',581                        originalname: '1MB.jpg',582                        name: res2.body[0].name,583                        encoding: '7bit',584                        mimetype: 'image/jpeg',585                        path: res2.body[0].path,586                        extension: 'jpg',587                        size: 683709,588                        truncated: false,589                        buffer: null590                      }591                    ]);592                    done();593                  }));594              }));595          });596        }597      );598      it('should delete a file attachment',599        function(done) {600          // Create a 200 response to return a file601          api.paths['/pets/{PetName}/photos'].delete.responses[200] = {602            description: '200 response',603            schema: {604              type: 'array',605              items: {606                type: 'file'607              }608            },609            headers: {610              'location': {611                type: 'string'612              },613              'content-disposition': {614                type: 'string'615              }616            }617          };618          helper.initTest(api, function(supertest) {619            // Save a pet photo (multipart/form-data)620            supertest621              .post('/api/pets/Fido/photos')622              .field('Label', 'Photo 1')623              .field('Description', 'A photo of Fido')624              .attach('Photo', files.paths.oneMB)625              .expect(201)626              .end(helper.checkResults(done, function() {627                // Delete the photo628                supertest629                  .delete('/api/pets/Fido/photos')630                  .expect('Content-Type', 'application/json; charset=utf-8')631                  .expect(200)632                  // Since there are multiple files, Content-Disposition is the "file name" of the URL633                  .expect('Content-Disposition', 'attachment; filename="photos"')634                  .end(helper.checkResults(done, function(res2) {635                    // There's no such thing as an "array of files",636                    // so we send back an array of file info637                    expect(res2.body).to.deep.equal([638                      {639                        fieldname: 'Photo',640                        originalname: '1MB.jpg',641                        name: res2.body[0].name,642                        encoding: '7bit',643                        mimetype: 'image/jpeg',644                        path: res2.body[0].path,645                        extension: 'jpg',646                        size: 683709,647                        truncated: false,648                        buffer: null649                      }650                    ]);651                    done();652                  }));653              }));654          });655        }656      );657    });658    describe('filter', function() {659      var Fido = {660        Name: 'Fido', Age: 4, Type: 'dog', Tags: ['big', 'brown'],661        Vet: {Name: 'Vet 1', Address: {Street: '123 First St.', City: 'New York', State: 'NY', ZipCode: 55555}}662      };663      var Fluffy = {664        Name: 'Fluffy', Age: 7, Type: 'cat', Tags: ['small', 'furry', 'white'],665        Vet: {Name: 'Vet 2', Address: {Street: '987 Second St.', City: 'Dallas', State: 'TX', ZipCode: 44444}}666      };667      var Polly = {668        Name: 'Polly', Age: 1, Type: 'bird', Tags: ['small', 'blue'],669        Vet: {Name: 'Vet 1', Address: {Street: '123 First St.', City: 'New York', State: 'NY', ZipCode: 55555}}670      };671      var Lassie = {672        Name: 'Lassie', Age: 7, Type: 'dog', Tags: ['big', 'furry', 'brown'],673        Vet: {Name: 'Vet 3', Address: {Street: '456 Pet Blvd.', City: 'Manhattan', State: 'NY', ZipCode: 56565}}674      };675      var Spot = {676        Name: 'Spot', Age: 4, Type: 'dog', Tags: ['big', 'spotted'],677        Vet: {Name: 'Vet 2', Address: {Street: '987 Second St.', City: 'Dallas', State: 'TX', ZipCode: 44444}}678      };679      var Garfield = {680        Name: 'Garfield', Age: 7, Type: 'cat', Tags: ['orange', 'fat'],681        Vet: {Name: 'Vet 4', Address: {Street: '789 Pet Lane', City: 'New York', State: 'NY', ZipCode: 66666}}682      };683      var allPets = [Fido, Fluffy, Polly, Lassie, Spot, Garfield];684      var dataStore;685      beforeEach(function(done) {686        dataStore = new swagger.MemoryDataStore();687        var resources = allPets.map(function(pet) {688          return new swagger.Resource('/api/pets', pet.Name, pet);689        });690        dataStore.save(resources, done);691      });692      it('should filter by a string property',693        function(done) {694          helper.initTest(dataStore, api, function(supertest) {695            supertest696              .delete('/api/pets?Type=cat')697              .expect(200, [Fluffy, Garfield])698              .end(helper.checkResults(done, function() {699                // Verify that the right pets were deleted700                supertest701                  .get('/api/pets')702                  .expect(200, [Fido, Polly, Lassie, Spot])703                  .end(helper.checkResults(done));704              }));705          });706        }707      );708      it('should filter by a numeric property',709        function(done) {710          helper.initTest(dataStore, api, function(supertest) {711            supertest712              .delete('/api/pets?Age=4')713              .expect(200, [Fido, Spot])714              .end(helper.checkResults(done, function() {715                // Verify that the right pets were deleted716                supertest717                  .get('/api/pets')718                  .expect(200, [Fluffy, Polly, Lassie, Garfield])719                  .end(helper.checkResults(done));720              }));721          });722        }723      );724      it('should filter by an array property (single value)',725        function(done) {726          helper.initTest(dataStore, api, function(supertest) {727            supertest728              .delete('/api/pets?Tags=big')729              .expect(200, [Fido, Lassie, Spot])730              .end(helper.checkResults(done, function() {731                // Verify that the right pets were deleted732                supertest733                  .get('/api/pets')734                  .expect(200, [Fluffy, Polly, Garfield])735                  .end(helper.checkResults(done));736              }));737          });738        }739      );740      it('should filter by an array property (multiple values, comma-separated)',741        function(done) {742          helper.initTest(dataStore, api, function(supertest) {743            supertest744              .delete('/api/pets?Tags=big,brown')745              .expect(200, [Fido, Lassie])746              .end(helper.checkResults(done, function() {747                // Verify that the right pets were deleted748                supertest749                  .get('/api/pets')750                  .expect(200, [Fluffy, Polly, Spot, Garfield])751                  .end(helper.checkResults(done));752              }));753          });754        }755      );756      it('should filter by an array property (multiple values, pipe-separated)',757        function(done) {758          _.find(api.paths['/pets'].delete.parameters, {name: 'Tags'}).collectionFormat = 'pipes';759          helper.initTest(dataStore, api, function(supertest) {760            supertest761              .delete('/api/pets?Tags=big|brown')762              .expect(200, [Fido, Lassie])763              .end(helper.checkResults(done, function() {764                // Verify that the right pets were deleted765                supertest766                  .get('/api/pets')767                  .expect(200, [Fluffy, Polly, Spot, Garfield])768                  .end(helper.checkResults(done));769              }));770          });771        }772      );773      it('should filter by an array property (multiple values, space-separated)',774        function(done) {775          _.find(api.paths['/pets'].delete.parameters, {name: 'Tags'}).collectionFormat = 'ssv';776          helper.initTest(dataStore, api, function(supertest) {777            supertest778              .delete('/api/pets?Tags=big%20brown')779              .expect(200, [Fido, Lassie])780              .end(helper.checkResults(done, function() {781                // Verify that the right pets were deleted782                supertest783                  .get('/api/pets')784                  .expect(200, [Fluffy, Polly, Spot, Garfield])785                  .end(helper.checkResults(done));786              }));787          });788        }789      );790      it('should filter by an array property (multiple values, repeated)',791        function(done) {792          helper.initTest(dataStore, api, function(supertest) {793            supertest794              .delete('/api/pets?Tags=big&Tags=brown')795              .expect(200, [Fido, Lassie])796              .end(helper.checkResults(done, function() {797                // Verify that the right pets were deleted798                supertest799                  .get('/api/pets')800                  .expect(200, [Fluffy, Polly, Spot, Garfield])801                  .end(helper.checkResults(done));802              }));803          });804        }805      );806      it('should filter by multiple properties',807        function(done) {808          helper.initTest(dataStore, api, function(supertest) {809            supertest810              .delete('/api/pets?Age=7&Type=cat&Tags=orange')811              .expect(200, [Garfield])812              .end(helper.checkResults(done, function() {813                // Verify that the right pets were deleted814                supertest815                  .get('/api/pets')816                  .expect(200, [Fido, Fluffy, Polly, Lassie, Spot])817                  .end(helper.checkResults(done));818              }));819          });820        }821      );822      it('should filter by a deep property',823        function(done) {824          helper.initTest(dataStore, api, function(supertest) {825            supertest826              .delete('/api/pets?Vet.Address.State=NY')827              .expect(200, [Fido, Polly, Lassie, Garfield])828              .end(helper.checkResults(done, function() {829                // Verify that the right pets were deleted830                supertest831                  .get('/api/pets')832                  .expect(200, [Fluffy, Spot])833                  .end(helper.checkResults(done));834              }));835          });836        }837      );838      it('should filter by multiple deep properties',839        function(done) {840          helper.initTest(dataStore, api, function(supertest) {841            supertest842              .delete('/api/pets?Vet.Address.State=NY&Vet.Address.City=New%20York')843              .expect(200, [Fido, Polly, Garfield])844              .end(helper.checkResults(done, function() {845                // Verify that the right pets were deleted846                supertest847                  .get('/api/pets')848                  .expect(200, [Fluffy, Lassie, Spot])849                  .end(helper.checkResults(done));850              }));851          });852        }853      );854      it('should not filter by properties that aren\'t defined in the Swagger API',855        function(done) {856          helper.initTest(dataStore, api, function(supertest) {857            supertest858              .delete('/api/pets?Name=Lassie&Vet.Address.Street=123%20First%20St.')859              .expect(200, allPets)860              .end(helper.checkResults(done, function() {861                // Verify that the right pets were deleted862                supertest863                  .get('/api/pets')864                  .expect(200, [])865                  .end(helper.checkResults(done));866              }));867          });868        }869      );870      it('should only filter by properties that are defined in the Swagger API',871        function(done) {872          helper.initTest(dataStore, api, function(supertest) {873            supertest874              .delete('/api/pets?Age=4&Name=Lassie&Vet.Name=Vet%202&Vet.Address.Street=123%20First%20St.')875              .expect(200, [Spot])876              .end(helper.checkResults(done, function() {877                // Verify that the right pets were deleted878                supertest879                  .get('/api/pets')880                  .expect(200, [Fido, Fluffy, Polly, Lassie, Garfield])881                  .end(helper.checkResults(done));882              }));883          });884        }885      );886    });887  });...

Full Screen

Full Screen

route.spec.js

Source:route.spec.js Github

copy

Full Screen

...45    const Route = use('Route')46    Route.get('/', async function () {47      return 'Hello world'48    })49    const res = await supertest(appUrl).get('/').expect(200)50    assert.equal(res.text, 'Hello world')51  })52  test('route without forward slash should work fine', async (assert) => {53    const Route = use('Route')54    const users = [{ username: 'virk' }, { username: 'nikk' }]55    Route.get('user', async function () {56      return users57    })58    assert.deepEqual((await supertest(appUrl).get('/user').expect(200)).body, users)59  })60  test('route resources should return 200', async (assert) => {61    const Route = use('Route')62    ioc.fake('App/Controllers/Http/UserController', function () {63      return new UserController()64    })65    Route.resource('users', 'UserController')66    assert.equal((await supertest(appUrl).get('/users').expect(200)).text, 'all')67    assert.equal((await supertest(appUrl).get('/users/create').expect(200)).text, 'form')68    assert.equal((await supertest(appUrl).post('/users').expect(200)).text, 'stored')69    assert.equal((await supertest(appUrl).get('/users/1').expect(200)).text, 'one')70    assert.equal((await supertest(appUrl).get('/users/1/edit').expect(200)).text, 'one-form')71    assert.equal((await supertest(appUrl).put('/users/1').expect(200)).text, 'updated')72    assert.equal((await supertest(appUrl).delete('/users/1').expect(200)).text, 'destroyed')73  })74  test('route resource with apiOnly do not register forms route', async (assert) => {75    const Route = use('Route')76    ioc.fake('App/Controllers/Http/UserController', function () {77      return new UserController()78    })79    Route.resource('users', 'UserController').apiOnly()80    assert.equal((await supertest(appUrl).get('/users').expect(200)).text, 'all')81    assert.equal((await supertest(appUrl).get('/users/create').expect(200)).text, 'one')82    assert.equal((await supertest(appUrl).post('/users').expect(200)).text, 'stored')83    assert.equal((await supertest(appUrl).get('/users/1').expect(200)).text, 'one')84    await supertest(appUrl).get('/users/1/edit')85    assert.equal((await supertest(appUrl).put('/users/1').expect(200)).text, 'updated')86    assert.equal((await supertest(appUrl).delete('/users/1').expect(200)).text, 'destroyed')87  })88  test('prefix routes inside a group', async (assert) => {89    const Route = use('Route')90    Route.group(function () {91      Route.get('/', function () {92        return 'api home'93      })94      Route.get('/about', function () {95        return 'api about'96      })97    }).prefix('api/v1')98    assert.equal((await supertest(appUrl).get('/api/v1').expect(200)).text, 'api home')99    assert.equal((await supertest(appUrl).get('/api/v1/about').expect(200)).text, 'api about')100  })101  test('prefix resource inside a group', async (assert) => {102    const Route = use('Route')103    ioc.fake('App/Controllers/Http/UserController', function () {104      return new UserController()105    })106    Route.group(function () {107      Route.resource('users', 'UserController')108    }).prefix('api/v1')109    assert.equal((await supertest(appUrl).get('/api/v1/users').expect(200)).text, 'all')110    assert.equal((await supertest(appUrl).get('/api/v1/users/create').expect(200)).text, 'form')111    assert.equal((await supertest(appUrl).post('/api/v1/users').expect(200)).text, 'stored')112    assert.equal((await supertest(appUrl).get('/api/v1/users/1').expect(200)).text, 'one')113    assert.equal((await supertest(appUrl).get('/api/v1/users/1/edit').expect(200)).text, 'one-form')114    assert.equal((await supertest(appUrl).put('/api/v1/users/1').expect(200)).text, 'updated')115    assert.equal((await supertest(appUrl).delete('/api/v1/users/1').expect(200)).text, 'destroyed')116  })117  test('add formats to resource', async (assert) => {118    const Route = use('Route')119    ioc.fake('App/Controllers/Http/UserController', function () {120      return new UserController()121    })122    Route.resource('users', 'UserController').formats(['json'], true)123    assert.equal((await supertest(appUrl).get('/users.json').expect(200)).text, 'all')124    assert.equal((await supertest(appUrl).get('/users/create.json').expect(200)).text, 'form')125    assert.equal((await supertest(appUrl).post('/users.json').expect(200)).text, 'stored')126    assert.equal((await supertest(appUrl).get('/users/1.json').expect(200)).text, 'one')127    assert.equal((await supertest(appUrl).get('/users/1/edit.json').expect(200)).text, 'one-form')128    assert.equal((await supertest(appUrl).put('/users/1.json').expect(200)).text, 'updated')129    assert.equal((await supertest(appUrl).delete('/users/1.json').expect(200)).text, 'destroyed')130  })131  test('add formats to group', async (assert) => {132    const Route = use('Route')133    ioc.fake('App/Controllers/Http/UserController', function () {134      return new UserController()135    })136    Route.group(() => {137      Route.resource('users', 'UserController')138    }).formats(['json'], true)139    assert.equal((await supertest(appUrl).get('/users.json').expect(200)).text, 'all')140    assert.equal((await supertest(appUrl).get('/users/create.json').expect(200)).text, 'form')141    assert.equal((await supertest(appUrl).post('/users.json').expect(200)).text, 'stored')142    assert.equal((await supertest(appUrl).get('/users/1.json').expect(200)).text, 'one')143    assert.equal((await supertest(appUrl).get('/users/1/edit.json').expect(200)).text, 'one-form')144    assert.equal((await supertest(appUrl).put('/users/1.json').expect(200)).text, 'updated')145    assert.equal((await supertest(appUrl).delete('/users/1.json').expect(200)).text, 'destroyed')146  })147  test('add middleware to route', async (assert) => {148    const Route = use('Route')149    Route.get('/', function ({ request }) {150      return request.foo151    }).middleware(function ({ request }, next) {152      request.foo = 'bar'153      return next()154    })155    assert.equal((await supertest(appUrl).get('/').expect(200)).text, 'bar')156  })157  test('add middleware to group', async (assert) => {158    const Route = use('Route')159    Route.group(() => {160      Route.get('/', function ({ request }) {161        return request.foo162      })163      Route.get('/foo', function ({ request }) {164        return request.foo165      })166    }).middleware(function ({ request }, next) {167      request.foo = 'bar'168      return next()169    })170    assert.equal((await supertest(appUrl).get('/').expect(200)).text, 'bar')171    assert.equal((await supertest(appUrl).get('/foo').expect(200)).text, 'bar')172  })173  test('add middleware to resource', async (assert) => {174    const Route = use('Route')175    ioc.fake('App/Controllers/Http/UserController', function () {176      return new UserController()177    })178    Route179      .resource('users', 'UserController')180      .middleware([181        async ({ response }, next) => {182          await next()183          response._lazyBody.content = response._lazyBody.content + ' via middleware'184        }185      ])186    assert.equal((await supertest(appUrl).get('/users').expect(200)).text, 'all via middleware')187    assert.equal((await supertest(appUrl).get('/users/create').expect(200)).text, 'form via middleware')188    assert.equal((await supertest(appUrl).post('/users').expect(200)).text, 'stored via middleware')189    assert.equal((await supertest(appUrl).get('/users/1').expect(200)).text, 'one via middleware')190    assert.equal((await supertest(appUrl).get('/users/1/edit').expect(200)).text, 'one-form via middleware')191    assert.equal((await supertest(appUrl).put('/users/1').expect(200)).text, 'updated via middleware')192    assert.equal((await supertest(appUrl).delete('/users/1').expect(200)).text, 'destroyed via middleware')193  })194  test('render view with data via brisk route', async (assert) => {195    const Route = use('Route')196    Route.on('/').render('user', { name: 'virk' })197    assert.equal((await supertest(appUrl).get('/').expect(200)).text.trim(), 'Hello virk')198  })199  test('respond to all routes via *', async (assert) => {200    const Route = use('Route')201    Route.any('(.*)', ({ request }) => request.url())202    assert.equal((await supertest(appUrl).get('/users').expect(200)).text, '/users')203    assert.equal((await supertest(appUrl).get('/users/create').expect(200)).text, '/users/create')204    assert.equal((await supertest(appUrl).post('/users').expect(200)).text, '/users')205    assert.equal((await supertest(appUrl).get('/users/1').expect(200)).text, '/users/1')206    assert.equal((await supertest(appUrl).get('/users/1/edit').expect(200)).text, '/users/1/edit')207    assert.equal((await supertest(appUrl).put('/users/1').expect(200)).text, '/users/1')208    assert.equal((await supertest(appUrl).delete('/users/1').expect(200)).text, '/users/1')209  })210  test('get route format via request.format', async (assert) => {211    const Route = use('Route')212    Route.get('users', ({ request }) => request.format()).formats(['json', 'xml'])213    assert.equal((await supertest(appUrl).get('/users.json').expect(200)).text, 'json')214    assert.equal((await supertest(appUrl).get('/users.xml').expect(200)).text, 'xml')215    assert.equal((await supertest(appUrl).get('/users').expect(204)).text, '')216  })...

Full Screen

Full Screen

supertest_v5.x.x.js

Source:supertest_v5.x.x.js Github

copy

Full Screen

1// flow-typed signature: 8aa950bdcd8ba645a0fcc2d2e3e20f072// flow-typed version: f87d4bcad8/supertest_v5.x.x/flow_>=v0.94.x3declare module 'supertest' {4  import type { IncomingMessage, ServerResponse } from 'http';5  import type { ReadStream as fs$ReadStream } from 'fs';6  // ----- Types from superagent -----7  declare type superagent$ResponseError = {|8    status: number,9    text: string,10    method: string,11    path: string,12  |} & Error;13  declare type superagent$Response = {|14    text?: string, // Present for text/json/urlencoded answers.15    body: any,16    type: string,17    xhr: XMLHttpRequest,18    redirects: string[],19    charset?: string, // This is decoded from the content-type20    error: superagent$ResponseError | false,21    files: any,22    get(header: string): string,23    get(header: 'Set-Cookie'): string[],24    headers: {| [key: string]: string |},25    header: {| [key: string]: string |},26    links: {| [key: string]: string |},27    // status numbers28    status: number,29    statusCode: number,30    statusType: 1 | 2 | 3 | 4 | 5,31    // Status boolean32    info: boolean, // 1xx33    ok: boolean, // 2xx34    redirect: boolean, // 3xx35    clientError: boolean, // 4xx36    serverError: boolean, // 5xx37    created: boolean, // 20138    accepted: boolean, // 20239    noContent: boolean, // 20440    badRequest: boolean, // 40041    unauthorized: boolean, // 40142    forbidden: boolean, // 40343    notFound: boolean, // 40444    notAcceptable: boolean, // 40645    unprocessableEntity: boolean, // 42246  |} & stream$Readable;47  declare type MultipartValueSingle =48    | Blob49    | Buffer50    | fs$ReadStream51    | string52    | boolean53    | number;54  declare type MultipartValue = MultipartValueSingle | MultipartValueSingle[];55  declare type superagent$CallbackHandler = (56    err: any,57    res: superagent$Response58  ) => mixed;59  declare type superagent$BrowserParser = (str: string) => mixed;60  declare type superagent$NodeParser = (61    res: superagent$Response,62    callback: (err: Error | null, body: any) => void63  ) => void;64  declare type superagent$Parser =65    | superagent$BrowserParser66    | superagent$NodeParser;67  // We declare only the event emitted from node. The one in the browser is68  // quite different.69  declare type superagent$ProgressEvent = {|70    direction: 'upload',71    loaded: number,72    lengthComputable: true,73    total: number,74  |};75  // Note: superagent$Request should inherit from both a Promise and a node76  // Stream, but I don't know how to do it with Flow... I decided to use the77  // Promise because it's likely more useful.78  declare class superagent$Request extends Promise<superagent$Response> {79    called: boolean;80    abort(): void;81    accept(type: string): this;82    attach(83      field: string,84      file: MultipartValueSingle,85      options?:86        | string87        | {|88            filename: string,89            contentType?: string,90          |}91    ): this;92    auth(93      user: string,94      pass: string,95      options?: {|96        type: 'basic' | 'auto', // "auto" isn't available in node97      |}98    ): this;99    auth(100      token: string,101      options: {|102        type: 'bearer',103      |}104    ): this;105    buffer(val?: boolean): this;106    ca(cert: string | string[] | Buffer | Buffer[]): this;107    cert(cert: string | string[] | Buffer | Buffer[]): this;108    clearTimeout(): this;109    // Removing it here because it's overriden below in supertest, and Flow110    // doesn't let the override work because the return value is different.111    // end(callback?: superagent$CallbackHandler): void;112    field(name: string, val: MultipartValue): this;113    field(fields: {|114      [fieldName: string]: MultipartValue,115    |}): this;116    get(field: string): string;117    key(cert: string | string[] | Buffer | Buffer[]): this;118    ok(callback: (res: superagent$Response) => boolean): this;119    on(name: 'error', handler: (err: any) => void): this;120    on(121      name: 'progress',122      handler: (event: superagent$ProgressEvent) => void123    ): this;124    on(125      name: 'response',126      handler: (response: superagent$Response) => void127    ): this;128    on(name: string, handler: (event: any) => void): this;129    parse(parser: superagent$Parser): this;130    part(): this;131    pfx(132      cert:133        | string134        | string[]135        | Buffer136        | Buffer[]137        | {|138            pfx: string | Buffer,139            passphrase: string,140          |}141    ): this;142    pipe(143      stream: stream$Writable,144      options?: {| end: boolean |}145    ): stream$Writable;146    query(val: { ... } | string): this;147    redirects(n: number): this;148    responseType(type: string): this;149    retry(count?: number, callback?: (err: any, res: superagent$Response) => boolean | void): this;150    send(data?: string | { ... }): this;151    serialize(serializer: (any) => string): this;152    set(field: { ... }): this;153    set(field: string, val: string): this;154    set(field: 'Cookie', val: string[]): this;155    timeout(156      ms:157        | number158        | {|159            deadline?: number,160            response?: number,161          |}162    ): this;163    type(val: string): this;164    unset(field: string): this;165    // use(fn: request$Plugin): this; TODO No support for plugins166    withCredentials(): this;167    write(data: string | Buffer, encoding?: string): this;168    maxResponseSize(size: number): this;169  }170  // ----- Types from supertest -----171  declare type supertest$RequestFunction = (url: string) => supertest$Test;172  // Possible HTTP requests.173  declare type supertest$Request = {|174    acl: supertest$RequestFunction,175    bind: supertest$RequestFunction,176    checkout: supertest$RequestFunction,177    connect: supertest$RequestFunction,178    copy: supertest$RequestFunction,179    delete: supertest$RequestFunction,180    del: supertest$RequestFunction,181    get: supertest$RequestFunction,182    head: supertest$RequestFunction,183    link: supertest$RequestFunction,184    lock: supertest$RequestFunction,185    'm-search': supertest$RequestFunction,186    merge: supertest$RequestFunction,187    mkactivity: supertest$RequestFunction,188    mkcalendar: supertest$RequestFunction,189    mkcol: supertest$RequestFunction,190    move: supertest$RequestFunction,191    notify: supertest$RequestFunction,192    options: supertest$RequestFunction,193    patch: supertest$RequestFunction,194    post: supertest$RequestFunction,195    propfind: supertest$RequestFunction,196    proppatch: supertest$RequestFunction,197    purge: supertest$RequestFunction,198    put: supertest$RequestFunction,199    rebind: supertest$RequestFunction,200    report: supertest$RequestFunction,201    search: supertest$RequestFunction,202    source: supertest$RequestFunction,203    subscribe: supertest$RequestFunction,204    trace: supertest$RequestFunction,205    unbind: supertest$RequestFunction,206    unlink: supertest$RequestFunction,207    unlock: supertest$RequestFunction,208    unsubscribe: supertest$RequestFunction,209  |};210  declare type supertest$BodyAssertion = RegExp | string | { ... };211  declare class supertest$Test extends superagent$Request {212    constructor(213      app: http$Server | string,214      method: string,215      path: string,216      host?: string217    ): this;218    app: http$Server | string;219    url: string;220    // ASSERTIONS221    // Queue a status assertion222    expect(status: number, callback?: superagent$CallbackHandler): this;223    // Queue a status and body assertion224    expect(225      status: number,226      body: supertest$BodyAssertion,227      callback?: superagent$CallbackHandler228    ): this;229    // Queue a body assertion230    expect(231      body: supertest$BodyAssertion,232      callback?: superagent$CallbackHandler233    ): this;234    // Queue a header assertion235    expect(236      field: string,237      val: string | number | RegExp,238      callback?: superagent$CallbackHandler239    ): this;240    // Queue a generic assertion241    // Note: it should appear after all other `expect` shapes because otherwise242    // Flow has problems selecting the right form.243    expect(checker: (res: superagent$Response) => mixed): this;244    // Run the queued assertions245    end(callback?: superagent$CallbackHandler): this;246  }247  // Accepted arguments to the supertest function.248  declare type supertest$Server =249    | string250    | http$Server251    | (<I: IncomingMessage, R: ServerResponse>(I, R) => void);252  declare module.exports: {|253    (server: supertest$Server): supertest$Request,254    Test: supertest$Test,255    // TODO implement a proper supertest$agent256    agent: any,257  |};...

Full Screen

Full Screen

response.spec.js

Source:response.spec.js Github

copy

Full Screen

1var swagger    = require('../../../'),2    expect     = require('chai').expect,3    _          = require('lodash'),4    files      = require('../../fixtures/files'),5    helper     = require('./helper');6describe('Mock Response', function() {7  'use strict';8  var api;9  beforeEach(function() {10    api = _.cloneDeep(files.parsed.petStore);11  });12  it('should use the 200 response, if it exists',13    function(done) {14      api.paths['/pets'].get.responses = {15        '100': {description: ''},16        '204': {description: ''},17        'default': {description: ''},18        '300': {description: ''},19        '200': {description: ''},20        '400': {description: ''}21      };22      helper.initTest(api, function(supertest) {23        supertest24          .get('/api/pets')25          .expect(200)26          .end(helper.checkResults(done));27      });28    }29  );30  it('should use the lowest 2XX response that exists',31    function(done) {32      api.paths['/pets'].get.responses = {33        '100': {description: ''},34        '204': {description: ''},35        'default': {description: ''},36        '203': {description: ''},37        '201': {description: ''},38        '102': {description: ''},39        '404': {description: ''}40      };41      helper.initTest(api, function(supertest) {42        supertest43          .get('/api/pets')44          .expect(201)45          .end(helper.checkResults(done));46      });47    }48  );49  it('should use the lowest 3XX response that exists',50    function(done) {51      api.paths['/pets'].get.responses = {52        '100': {description: ''},53        '304': {description: ''},54        'default': {description: ''},55        '302': {description: ''},56        '303': {description: ''},57        '400': {description: ''}58      };59      helper.initTest(api, function(supertest) {60        supertest61          .get('/api/pets')62          .expect(302)63          .end(helper.checkResults(done));64      });65    }66  );67  it('should use the lowest 1XX response that exists',68    function(done) {69      api.paths['/pets'].get.responses = {70        '102': {description: ''},71        '404': {description: ''},72        '500': {description: ''},73        '101': {description: ''},74        '400': {description: ''},75        '504': {description: ''}76      };77      helper.initTest(api, function(supertest) {78        supertest79          .get('/api/pets')80          .expect(101)81          .end(helper.checkResults(done));82      });83    }84  );85  it('should use a 200 response if "default" exists',86    function(done) {87      api.paths['/pets'].get.responses = {88        '100': {description: ''},89        '400': {description: ''},90        'default': {description: ''},91        '402': {description: ''},92        '500': {description: ''},93        '102': {description: ''}94      };95      helper.initTest(api, function(supertest) {96        supertest97          .get('/api/pets')98          .expect(200)99          .end(helper.checkResults(done));100      });101    }102  );103  it('should use a 201 response for POST operations if "default" exists',104    function(done) {105      api.paths['/pets'].post.responses = {106        '100': {description: ''},107        '400': {description: ''},108        'default': {description: ''},109        '402': {description: ''},110        '500': {description: ''},111        '102': {description: ''}112      };113      helper.initTest(api, function(supertest) {114        supertest115          .post('/api/pets')116          .send({Name: 'Fido', Type: 'dog'})117          .expect(201)118          .end(helper.checkResults(done));119      });120    }121  );122  it('should not use a 201 response for POST operations if "default" does not exist',123    function(done) {124      api.paths['/pets'].post.responses = {125        '400': {description: ''},126        '402': {description: ''},127        '500': {description: ''},128        '102': {description: ''}129      };130      helper.initTest(api, function(supertest) {131        supertest132          .post('/api/pets')133          .send({Name: 'Fido', Type: 'dog'})134          .expect(102)135          .end(helper.checkResults(done));136      });137    }138  );139  it('should use a 201 response for PUT operations if "default" exists',140    function(done) {141      api.paths['/pets'].put = api.paths['/pets'].post;142      api.paths['/pets'].put.responses = {143        '100': {description: ''},144        '400': {description: ''},145        'default': {description: ''},146        '402': {description: ''},147        '500': {description: ''},148        '102': {description: ''}149      };150      helper.initTest(api, function(supertest) {151        supertest152          .put('/api/pets')153          .send({Name: 'Fido', Type: 'dog'})154          .expect(201)155          .end(helper.checkResults(done));156      });157    }158  );159  it('should not use a 201 response for PUT operations if "default" does not exist',160    function(done) {161      api.paths['/pets'].put = api.paths['/pets'].post;162      api.paths['/pets'].put.responses = {163        '101': {description: ''},164        '400': {description: ''},165        '402': {description: ''},166        '500': {description: ''},167        '102': {description: ''}168      };169      helper.initTest(api, function(supertest) {170        supertest171          .put('/api/pets')172          .send({Name: 'Fido', Type: 'dog'})173          .expect(101)174          .end(helper.checkResults(done));175      });176    }177  );178  it('should use a 204 response for DELETE operations if "default" exists',179    function(done) {180      api.paths['/pets/{PetName}'].delete.responses = {181        '100': {description: ''},182        '400': {description: ''},183        'default': {description: ''},184        '402': {description: ''},185        '500': {description: ''},186        '102': {description: ''}187      };188      helper.initTest(api, function(supertest) {189        supertest190          .delete('/api/pets/Fido')191          .expect(204)192          .end(helper.checkResults(done));193      });194    }195  );196  it('should not use a 204 response for DELETE operations if "default" does not exist',197    function(done) {198      api.paths['/pets/{PetName}'].delete.responses = {199        '101': {description: ''},200        '400': {description: ''},201        '402': {description: ''},202        '500': {description: ''},203        '102': {description: ''}204      };205      helper.initTest(api, function(supertest) {206        supertest207          .delete('/api/pets/Fido')208          .expect(101)209          .end(helper.checkResults(done));210      });211    }212  );...

Full Screen

Full Screen

main.test.js

Source:main.test.js Github

copy

Full Screen

...5global.console.log = msg => consoleLogMock(msg);6beforeAll(async () => {7  await require("../../data").initializeDatabase();8});9const supertestServer = supertest(server);10afterAll(() => {11  server.close();12});13describe("Express server starts server", () => {14  it("gives a response when accessing '/'", async () => {15    const response = await supertestServer.get("/");16    expect(response.status).not.toBe(200);17  });18});19describe("Accessing /", () => {20  it("yields response", async () => {21    const response = await supertestServer.get("/");22    expect(response.header.location).toBe("/graphql");23  });...

Full Screen

Full Screen

test.js

Source:test.js Github

copy

Full Screen

...13    "YxODYyNjM4MCwiZXhwIjoxNjE5MDU4MzgwfQ.gsG1g4dtn-Q-4XhPcLCZUED3jpnfG7_ZhrirStY2Ux8";14const test_data = { name: "test", email: "test@gmail.com", password: "123456" };15// create new user16// test("POST /api/user", async () => {17//     await supertest(app)18//         .post("/api/user")19//         .type('json')20//         .send(test_data)21//         .expect(200)22//         .then(async (res) => {23//             auth_token = await res.body['token'];24//             console.log(auth_token)25//         })26// });27// new user auth28test("GET /api/auth", async () => {29    await supertest(app)30        .get("/api/auth")31        .set('auth-token', auth_token)32        .expect(200)33        .then(async (res) => {34            expect(res.body.email).toBe(test_data.email)35        })36});37// user auth, not exist38test("GET /api/auth", async () => {39    await supertest(app)40        .get("/api/auth")41        .set('auth-token', "")42        .expect(401)43});44// authenticate user & get token45test("POST /api/auth", async () => {46    await supertest(app)47        .post("/api/auth")48        .type('json')49        .send({ email: "test@gmail.com", password: "123456" })50        .expect(200)51});52// authenticate user & get token, user doesn't exist53test("POST /api/auth", async () => {54    await supertest(app)55        .post("/api/auth")56        .type('json')57        .send({ email: "test@illinois.edu", password: "123456" })58        .expect(400)59});60// authenticate user & get token, password not match61test("POST /api/auth", async () => {62    await supertest(app)63        .post("/api/auth")64        .type('json')65        .send({ email: "test@gmail.com", password: "1234567" })66        .expect(400)67});68// User already existed69test("POST /api/user", async () => {70    await supertest(app)71        .post("/api/user")72        .type('json')73        .send({ name: "test", email: "test@gmail.com", password: "123456" })74        .expect(400)75});76// User created, no password provided77test("POST /api/user", async () => {78    await supertest(app)79        .post("/api/user")80        .type('json')81        .send({ name: "test", email: "test@gmail.com" })82        .expect(400)83});84// User created, no password length < 685test("POST /api/user", async () => {86    await supertest(app)87        .post("/api/user")88        .type('json')89        .send({ name: "test", email: "test@gmail.com", password: "123456" })90        .expect(400)91});92// User created, no email provided93test("POST /api/user", async () => {94    await supertest(app)95        .post("/api/user")96        .type('json')97        .send({ name: "test", password: "123456" })98        .expect(400)99});100// User created, no name provided101test("POST /api/user", async () => {102    await supertest(app)103        .post("/api/user")104        .type('json')105        .send({ email: "test@gmail.com", password: "123456" })106        .expect(400)107});108// get current user infomation109test("GET /api/user/me", async () => {110    await supertest(app)111        .get("/api/user/me")112        .set('auth-token', auth_token)113        .expect(200)114});115// get current user infomation, doesn't exist116test("GET /api/user/me", async () => {117    await supertest(app)118        .get("/api/user/me")119        .set('auth-token', "")120        .expect(401)121});122// update password123test("PUT /api/user", async () => {124    await supertest(app)125        .put("/api/user/me/password")126        .set('auth-token', auth_token)127        .type('json')128        .send({ password: "1234567" })129        .expect(200)130});131// authenticate user & get token after password update132test("POST /api/auth", async () => {133    await supertest(app)134        .post("/api/auth")135        .type('json')136        .send({ email: "test@gmail.com", password: "1234567" })137        .expect(200)138});139// update password140test("PUT /api/user", async () => {141    await supertest(app)142        .put("/api/user/me/password")143        .set('auth-token', auth_token)144        .type('json')145        .send({ password: "" })146        .expect(400)147});148// update avatar149test("PUT /api/user/avatar", async () => {150    await supertest(app)151        .put("/api/user/me/avatar")152        .set('auth-token', auth_token)153        .type('json')154        .send({ avatar: "https://avatars.github-dev.cs.illinois.edu/u/4682?s=460" })155        .expect(200)156});157// update avatar158test("PUT /api/user/avatar", async () => {159    await supertest(app)160        .put("/api/user/me/avatar")161        .set('auth-token', auth_token)162        .type('json')163        .send({ avatar: "" })164        .expect(400)165});166// // delete current user167// test("DELETE /api/user/me", async () => {168//     await supertest(app)169//         .delete("/api/user/me")170//         .set('auth-token', auth_token)171//         .expect(200)172// });173// delete current user, doesn't exist 174test("DELETE /api/user/me", async () => {175    await supertest(app)176        .delete("/api/user/me")177        .set('auth-token', "")178        .expect(401)179});180afterAll(async (done) => {181    await mongoose.connection.close();182    done();...

Full Screen

Full Screen

supertest_vx.x.x.js

Source:supertest_vx.x.x.js Github

copy

Full Screen

1// flow-typed signature: 48454ae77884359456cbf79c53f641f52// flow-typed version: <<STUB>>/supertest_v^3.0.0/flow_v0.46.03/**4 * This is an autogenerated libdef stub for:5 *6 *   'supertest'7 *8 * Fill this stub out by replacing all the `any` types.9 *10 * Once filled out, we encourage you to share your work with the11 * community by sending a pull request to:12 * https://github.com/flowtype/flow-typed13 */14declare module 'supertest' {15  declare module.exports: any;16}17/**18 * We include stubs for each file inside this npm package in case you need to19 * require those files directly. Feel free to delete any files that aren't20 * needed.21 */22declare module 'supertest/lib/agent' {23  declare module.exports: any;24}25declare module 'supertest/lib/test' {26  declare module.exports: any;27}28declare module 'supertest/test/supertest' {29  declare module.exports: any;30}31// Filename aliases32declare module 'supertest/index' {33  declare module.exports: $Exports<'supertest'>;34}35declare module 'supertest/index.js' {36  declare module.exports: $Exports<'supertest'>;37}38declare module 'supertest/lib/agent.js' {39  declare module.exports: $Exports<'supertest/lib/agent'>;40}41declare module 'supertest/lib/test.js' {42  declare module.exports: $Exports<'supertest/lib/test'>;43}44declare module 'supertest/test/supertest.js' {45  declare module.exports: $Exports<'supertest/test/supertest'>;...

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.contains('type').click()4    cy.url().should('include', '/commands/actions')5    cy.get('.action-email')6      .type('

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('My First Test', function() {2  it('Does not do much!', function() {3    expect(true).to.equal(true)4  })5})6describe('My First Test', function() {7  it('Does not do much!', function() {8    expect(true).to.equal(true)9  })10})11describe('My First Test', function() {12  it('Does not do much!', function() {13    expect(true).to.equal(true)14  })15})16describe('My First Test', function() {17  it('Does not do much!', function() {18    expect(true).to.equal(true)19  })20})21describe('My First Test', function() {22  it('Does not do much!', function() {23    expect(true).to.equal(true)24  })25})26describe('My First Test', function() {27  it('Does not do much!', function() {28    expect(true).to.equal(true)29  })30})31describe('My First Test', function() {32  it('Does not do much!', function() {33    expect(true).to.equal(true)34  })35})36describe('My First Test', function() {37  it('Does not do much!', function() {38    expect(true).to.equal(true)39  })40})41describe('My First Test', function() {42  it('Does not do much!', function() {43    expect(true).to.equal(true)44  })45})46describe('My First Test', function() {47  it('Does not do much!', function() {48    expect(true).to.equal(true)49  })50})51describe('My First Test', function() {52  it('Does not do much!', function() {53    expect(true).to.equal(true)54  })55})56describe('My First Test', function() {57  it('Does not do much!', function() {58    expect(true).to.equal(true)59  })60})61describe('My First Test', function

Full Screen

Using AI Code Generation

copy

Full Screen

1const supertest = require('supertest')2const app = require('../app')3const request = supertest(app)4describe('Test the root path', () => {5  test('It should response the GET method', async () => {6    const response = await request.get('/')7    expect(response.statusCode).toBe(200)8  })9})10const express = require('express')11const app = express()12app.get('/', (req, res) => res.send('Hello World!'))13app.listen(port, () => console.log(`Example app listening on port ${port}!`))14{15  "env": {16  }17}18{19  "scripts": {20  },21  "devDependencies": {22  }23}24{25  "dependencies": {26    "@babel/code-frame": {27      "requires": {28      }29    },30    "@babel/compat-data": {

Full Screen

Using AI Code Generation

copy

Full Screen

1const supertest = require('supertest')2const app = require('./app')3const request = supertest(app)4describe('Test the root path', () => {5  test('It should response the GET method', async () => {6    const response = await request.get('/')7    expect(response.statusCode).toBe(200)8  })9})10const express = require('express')11const app = express()12app.get('/', (req, res) => {13  res.send('Hello World!')14})15const request = require('supertest');16const app = require('../app');17describe('Test the root path', () => {18  test('It should response the GET method', async () => {19    const response = await request(app).get('/');20    expect(response.statusCode).toBe(200);21  });22});23const express = require('express');24const app = express();25app.get('/', (req, res) => {26  res.send('Hello World!');27});28module.exports = app;

Full Screen

Using AI Code Generation

copy

Full Screen

1const supertest = require('supertest')2describe('My First Test', function() {3  it('Gets, visits the Kitchen Sink', function() {4  })5})6const supertest = require('supertest')7describe('My First Test', function() {8  it('Gets, visits the Kitchen Sink', function() {9  })10})11const supertest = require('supertest')12describe('My First Test', function() {13  it('Gets, visits the Kitchen Sink', function() {14  })15})16const supertest = require('supertest')17describe('My First Test', function() {18  it('Gets, visits the Kitchen Sink', function() {19  })20})21const supertest = require('supertest')22describe('My First Test', function() {23  it('Gets, visits the Kitchen Sink', function() {24  })25})26const supertest = require('supertest')27describe('My First Test', function() {28  it('Gets, visits the Kitchen Sink', function() {29  })30})31const supertest = require('supertest')32describe('My First Test', function() {33  it('Gets, visits the Kitchen Sink', function() {34  })35})36const supertest = require('supertest')37describe('My First Test', function() {38  it('Gets, visits the Kitchen Sink', function() {39  })40})41const supertest = require('supertest')42describe('My First Test', function() {43  it('Gets, visits the Kitchen Sink', function() {44  })45})

Full Screen

Using AI Code Generation

copy

Full Screen

1const supertest = require('supertest');2const chai = require('chai');3const chaiHttp = require('chai-http');4const expect = chai.expect;5const config = require('../../cypress.json');6const baseUrl = config.baseUrl;7const port = config.port;8const timeout = config.requestTimeout;9const headers = config.headers;10const auth = config.auth;11const username = config.username;12const password = config.password;13const user = config.user;14const pass = config.pass;15const url = config.url;16const apiUrl = config.apiUrl;17const api = config.api;18const urlApi = config.urlApi;19const apiUser = config.apiUser;20const apiPass = config.apiPass;21const apiUserPass = config.apiUserPass;22const apiUserPassUrl = config.apiUserPassUrl;23const apiUserPassUrlApi = config.apiUserPassUrlApi;24const apiUserPassUrlApiUser = config.apiUserPassUrlApiUser;25const apiUserPassUrlApiUserPass = config.apiUserPassUrlApiUserPass;26const apiUserPassUrlApiUserPassUrl = config.apiUserPassUrlApiUserPassUrl;27const apiUserPassUrlApiUserPassUrlApi = config.apiUserPassUrlApiUserPassUrlApi;

Full Screen

Using AI Code Generation

copy

Full Screen

1it('POST - Create new user', () => {2  cy.request({3    body: {4    }5  }).then((response) => {6    expect(response.status).to.eq(201)7    expect(response.body).to.have.property('name', 'morpheus')8    expect(response.body).to.have.property('job', 'leader')9  })10})11{12}13{14  "scripts": {15  },16  "devDependencies": {17  }18}

Full Screen

Using AI Code Generation

copy

Full Screen

1import 'cypress-file-upload';2import { login } from '../support/login';3import { upload } from '../support/upload';4import { download } from '../support/download';5describe('Test', () => {6  beforeEach(() => {7    login();8  });9  it('Upload file', () => {10    upload();11  });12  it('Download file', () => {13    download();14  });15});16export const login = () => {17  cy.get('input').type('test');18  cy.get('button').click();19};20export const upload = () => {21  cy.fixture('test.pdf').then(fileContent => {22    cy.get('input[type=file]').upload({23    });24  });25};26export const download = () => {27  cy.get('a').click();28};29const { addMatchImageSnapshotPlugin } = require('cypress-image-snapshot/plugin');30module.exports = (on, config) => {31  addMatchImageSnapshotPlugin(on, config);32};33import 'cypress-file-upload';34import 'cypress-image-snapshot/command';35import { addMatchImageSnapshotCommand } from 'cypress-image-snapshot/command';36addMatchImageSnapshotCommand();37import './commands';38{39  "reporterOptions": {

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