Best JavaScript code snippet using supertest
test.js
Source:test.js  
1'use strict';2/**3 * Module dependencies.4 */5var request = require('superagent');6var util = require('util');7var http = require('http');8var https = require('https');9var assert = require('assert');10var Request = request.Request;11/**12 * Expose `Test`.13 */14module.exports = Test;15/**16 * Initialize a new `Test` with the given `app`,17 * request `method` and `path`.18 *19 * @param {Server} app20 * @param {String} method21 * @param {String} path22 * @api public23 */24function Test(app, method, path) {25  Request.call(this, method.toUpperCase(), path);26  this.redirects(0);27  this.buffer();28  this.app = app;29  this._asserts = [];30  this.url = typeof app === 'string'31    ? app + path32    : this.serverAddress(app, path);33}34/**35 * Inherits from `Request.prototype`.36 */37Object.setPrototypeOf(Test.prototype, Request.prototype);38/**39 * Returns a URL, extracted from a server.40 *41 * @param {Server} app42 * @param {String} path43 * @returns {String} URL address44 * @api private45 */46Test.prototype.serverAddress = function(app, path) {47  var addr = app.address();48  var port;49  var protocol;50  if (!addr) this._server = app.listen(0);51  port = app.address().port;52  protocol = app instanceof https.Server ? 'https' : 'http';53  return protocol + '://127.0.0.1:' + port + path;54};55/**56 * Wraps an assert function into another.57 * The wrapper function edit the stack trace of any assertion error, prepending a more useful stack to it.58 *59 * @param {Function} assertFn60 * @returns {Function} wrapped assert function61 */62function wrapAssertFn(assertFn) {63  var savedStack = new Error().stack.split('\n').slice(3);64  return function(res) {65    var badStack;66    var err = assertFn(res);67    if (err instanceof Error && err.stack) {68      badStack = err.stack.replace(err.message, '').split('\n').slice(1);69      err.stack = [err.toString()]70        .concat(savedStack)71        .concat('----')72        .concat(badStack)73        .join('\n');74    }75    return err;76  };77}78/**79 * Expectations:80 *81 *   .expect(200)82 *   .expect(200, fn)83 *   .expect(200, body)84 *   .expect('Some body')85 *   .expect('Some body', fn)86 *   .expect(['json array body', { key: 'val' }])87 *   .expect('Content-Type', 'application/json')88 *   .expect('Content-Type', 'application/json', fn)89 *   .expect(fn)90 *   .expect([200, 404])91 *92 * @return {Test}93 * @api public94 */95Test.prototype.expect = function(a, b, c) {96  // callback97  if (typeof a === 'function') {98    this._asserts.push(wrapAssertFn(a));99    return this;100  }101  if (typeof b === 'function') this.end(b);102  if (typeof c === 'function') this.end(c);103  // status104  if (typeof a === 'number') {105    this._asserts.push(wrapAssertFn(this._assertStatus.bind(this, a)));106    // body107    if (typeof b !== 'function' && arguments.length > 1) {108      this._asserts.push(wrapAssertFn(this._assertBody.bind(this, b)));109    }110    return this;111  }112  // multiple statuses113  if (Array.isArray(a) && a.length > 0 && a.every(val => typeof val === 'number')) {114    this._asserts.push(wrapAssertFn(this._assertStatusArray.bind(this, a)));115    return this;116  }117  // header field118  if (typeof b === 'string' || typeof b === 'number' || b instanceof RegExp) {119    this._asserts.push(wrapAssertFn(this._assertHeader.bind(this, { name: '' + a, value: b })));120    return this;121  }122  // body123  this._asserts.push(wrapAssertFn(this._assertBody.bind(this, a)));124  return this;125};126/**127 * Defer invoking superagent's `.end()` until128 * the server is listening.129 *130 * @param {Function} fn131 * @api public132 */133Test.prototype.end = function(fn) {134  var self = this;135  var server = this._server;136  var end = Request.prototype.end;137  end.call(this, function(err, res) {138    if (server && server._handle) return server.close(localAssert);139    localAssert();140    function localAssert() {141      self.assert(err, res, fn);142    }143  });144  return this;145};146/**147 * Perform assertions and invoke `fn(err, res)`.148 *149 * @param {?Error} resError150 * @param {Response} res151 * @param {Function} fn152 * @api private153 */154Test.prototype.assert = function(resError, res, fn) {155  var errorObj;156  var i;157  // check for unexpected network errors or server not running/reachable errors158  // when there is no response and superagent sends back a System Error159  // do not check further for other asserts, if any, in such case160  // https://nodejs.org/api/errors.html#errors_common_system_errors161  var sysErrors = {162    ECONNREFUSED: 'Connection refused',163    ECONNRESET: 'Connection reset by peer',164    EPIPE: 'Broken pipe',165    ETIMEDOUT: 'Operation timed out'166  };167  if (!res && resError) {168    if (resError instanceof Error && resError.syscall === 'connect'169        && Object.getOwnPropertyNames(sysErrors).indexOf(resError.code) >= 0) {170      errorObj = new Error(resError.code + ': ' + sysErrors[resError.code]);171    } else {172      errorObj = resError;173    }174  }175  // asserts176  for (i = 0; i < this._asserts.length && !errorObj; i += 1) {177    errorObj = this._assertFunction(this._asserts[i], res);178  }179  // set unexpected superagent error if no other error has occurred.180  if (!errorObj && resError instanceof Error && (!res || resError.status !== res.status)) {181    errorObj = resError;182  }183  fn.call(this, errorObj || null, res);184};185/**186 * Perform assertions on a response body and return an Error upon failure.187 *188 * @param {Mixed} body189 * @param {Response} res190 * @return {?Error}191 * @api private192 */193Test.prototype._assertBody = function(body, res) {194  var isregexp = body instanceof RegExp;195  var a;196  var b;197  // parsed198  if (typeof body === 'object' && !isregexp) {199    try {200      assert.deepStrictEqual(body, res.body);201    } catch (err) {202      a = util.inspect(body);203      b = util.inspect(res.body);204      return error('expected ' + a + ' response body, got ' + b, body, res.body);205    }206  } else if (body !== res.text) {207    // string208    a = util.inspect(body);209    b = util.inspect(res.text);210    // regexp211    if (isregexp) {212      if (!body.test(res.text)) {213        return error('expected body ' + b + ' to match ' + body, body, res.body);214      }215    } else {216      return error('expected ' + a + ' response body, got ' + b, body, res.body);217    }218  }219};220/**221 * Perform assertions on a response header and return an Error upon failure.222 *223 * @param {Object} header224 * @param {Response} res225 * @return {?Error}226 * @api private227 */228Test.prototype._assertHeader = function(header, res) {229  var field = header.name;230  var actual = res.header[field.toLowerCase()];231  var fieldExpected = header.value;232  if (typeof actual === 'undefined') return new Error('expected "' + field + '" header field');233  // This check handles header values that may be a String or single element Array234  if ((Array.isArray(actual) && actual.toString() === fieldExpected)235    || fieldExpected === actual) {236    return;237  }238  if (fieldExpected instanceof RegExp) {239    if (!fieldExpected.test(actual)) {240      return new Error('expected "' + field + '" matching '241        + fieldExpected + ', got "' + actual + '"');242    }243  } else {244    return new Error('expected "' + field + '" of "' + fieldExpected + '", got "' + actual + '"');245  }246};247/**248 * Perform assertions on the response status and return an Error upon failure.249 *250 * @param {Number} status251 * @param {Response} res252 * @return {?Error}253 * @api private254 */255Test.prototype._assertStatus = function(status, res) {256  var a;257  var b;258  if (res.status !== status) {259    a = http.STATUS_CODES[status];260    b = http.STATUS_CODES[res.status];261    return new Error('expected ' + status + ' "' + a + '", got ' + res.status + ' "' + b + '"');262  }263};264/**265 * Perform assertions on the response status and return an Error upon failure.266 *267 * @param {Array<Number>} statusArray268 * @param {Response} res269 * @return {?Error}270 * @api private271 */272Test.prototype._assertStatusArray = function(statusArray, res) {273  var b;274  var expectedList;275  if (!statusArray.includes(res.status)) {276    b = http.STATUS_CODES[res.status];277    expectedList = statusArray.join(', ');278    return new Error('expected one of "' + expectedList + '", got ' + res.status + ' "' + b + '"');279  }280};281/**282 * Performs an assertion by calling a function and return an Error upon failure.283 *284 * @param {Function} fn285 * @param {Response} res286 * @return {?Error}287 * @api private288 */289Test.prototype._assertFunction = function(fn, res) {290  var err;291  try {292    err = fn(res);293  } catch (e) {294    err = e;295  }296  if (err instanceof Error) return err;297};298/**299 * Return an `Error` with `msg` and results properties.300 *301 * @param {String} msg302 * @param {Mixed} expected303 * @param {Mixed} actual304 * @return {Error}305 * @api private306 */307function error(msg, expected, actual) {308  var err = new Error(msg);309  err.expected = expected;310  err.actual = actual;311  err.showDiff = true;312  return err;...Using AI Code Generation
1var request = require('supertest');2var assert = require('assert');3describe('GET /users', function() {4  it('respond with json', function(done) {5    request(app)6      .get('/users')7      .set('Accept', 'application/json')8      .expect('Content-Type', /json/)9      .expect(200)10      .end(function(err, res) {11        if (err) return done(err);12        assert.equal(res.body.length, 3);13        done();14      });15  });16});17var request = require('supertest');18var assert = require('assert');19describe('GET /users', function() {20  it('respond with json', function(done) {21    request(app)22      .get('/users')23      .set('Accept', 'application/json')24      .expect('Content-Type', /json/)25      .expect(200)26      .end(function(err, res) {27        if (err) return done(err);28        assert.equal(res.body.length, 3);29        done();30      });31  });32});33var request = require('supertest');34var assert = require('assert');35describe('GET /users', function() {36  it('respond with json', function(done) {37    request(app)38      .get('/users')39      .set('Accept', 'application/json')40      .expect('Content-Type', /json/)41      .expect(200)42      .end(function(err, res) {43        if (err) return done(err);44        assert.equal(res.body.length, 3);45        done();46      });47  });48});49var request = require('supertest');50var assert = require('assert');51describe('GET /users', function() {52  it('respond with json', function(done) {53    request(app)54      .get('/users')55      .set('Accept', 'application/json')56      .expect('Content-Type', /json/)57      .expect(200)58      .end(function(err, res) {59        if (err) return done(err);60        assert.equal(res.body.length, 3);61        done();62      });63  });64});Using AI Code Generation
1var assert = require('assert');2var request = require('supertest');3var app = require('./app');4describe('GET /', function() {5  it('respond with json', function(done) {6    request(app)7      .get('/')8      .expect(200)9      .expect('Content-Type', /json/)10      .end(function(err, res) {11        if (err) return done(err);12        done();13      });14  });15});16var express = require('express');17var app = express();18app.get('/', function(req, res) {19  res.send({ message: 'hello world' });20});21module.exports = app;Using AI Code Generation
1var request = require('supertest');2var assert = require('assert');3var app = require('../app');4describe('GET /', function() {5  it('respond with json', function(done) {6    request(app)7      .get('/')8      .set('Accept', 'application/json')9      .expect('Content-Type', /json/)10      .expect(200)11      .end(function(err, res) {12        if (err) return done(err);13        assert.equal(res.body.status, 'OK');14        done();15      });16  });17});18var express = require('express');19var app = express();20app.get('/', function(req, res) {21  res.json({ status: 'OK' });22});23module.exports = app;24var request = require('supertest');25var assert = require('assert');26var app = require('../app');27describe('GET /', function() {28  it('respond with json', function(done) {29    request(app)30      .get('/')31      .set('Accept', 'application/json')32      .expect('Content-Type', /json/)33      .expect([200, 201])34      .end(function(err, res) {35        if (err) return done(err);36        assert.equal(res.body.status, 'OK');37        done();38      });39  });40});41var express = require('express');42var app = express();43app.get('/', function(req, res) {44  res.json({ status: 'OK' });45});46module.exports = app;Using AI Code Generation
1const request = require('supertest');2const app = require('./app.js');3describe('GET /', function() {4  it('respond with json containing a list of all users', function(done) {5    request(app)6      .get('/')7      .expect('Content-Type', /json/)8      .expect(200)9      .expect('Content-Type', /json/)10      .expect('Content-Length', '15')11      .expect(function(res) {12        if (!('name' in res.body)) throw new Error("missing 'name' property");13      })14      .end(function(err, res) {15        if (err) return done(err);16        done();17      });18  });19});20const express = require('express');21const app = express();22app.get('/', function(req, res) {23  res.status(200).send({ name: 'john' });24});25module.exports = app;26const request = require('supertest');27const app = require('./app.js');28describe('GET /', function() {29  it('respond with json containing a list of all users', function(done) {30    request(app)31      .get('/')32      .expect('Content-Type', /json/)33      .expect(200)34      .expect('Content-Type', /json/)35      .expect('Content-Length', '15')36      .expect(function(res) {37        if (!('name' in res.body)) throw new Error("missing 'name' property");38      })39      .end(function(err, res) {40        if (err) return done(err);41        done();42      });43  });44});45const express = require('express');46const app = express();47app.get('/', function(req, res) {48  res.status(200).send({ name: 'john' });49});50module.exports = app;51AssertionError: expected { Object (name, email) } to deeply equal { Object (name, email) }52  {Using AI Code Generation
1const request = require('supertest');2const app = require('../app');3const assert = require('assert');4describe('GET /users', function() {5  it('respond with json', function(done) {6    request(app)7      .get('/users')8      .set('Accept', 'application/json')9      .expect('Content-Type', /json/)10  });11});12const express = require('express');13const app = express();14app.get('/users', function(req, res) {15  res.status(200).json({});16});17module.exports = app;18{19  "scripts": {20  },21  "dependencies": {22  },23  "devDependencies": {24  }25}Using AI Code Generation
1var assert = require('assert');2var request = require('supertest');3var app = require('../app');4describe('GET /', function() {5    it('respond with 200', function(done) {6        request(app)7            .get('/')8            .expect(200, done);9    });10});11var express = require('express');12var app = express();13app.get('/', function(req, res) {14    res.send('Hello World!');15});16app.listen(3000);17var assert = require('assert');18var request = require('supertest');19var app = require('../app');20describe('GET /', function() {21    it('respond with 200', function(done) {22        request(app)23            .get('/')24            .expect([200, 201], done);25    });26});27var express = require('express');28var app = express();29app.get('/', function(req, res) {30    res.status(201).send('Hello World!');31});32app.listen(3000);33var assert = require('assert');34var request = require('supertest');35var app = require('../app');36describe('GET /', function() {37    it('respond with 200', function(done) {38        request(app)39            .get('/')40            .expect([200, 201, 202], done);41    });42});43var express = require('express');44var app = express();45app.get('/', function(req, res) {46    res.status(201).send('Hello World!');47});48app.listen(3000);Using AI Code Generation
1var assert = require('assert');2var app = require('../app');3var request = require('supertest')(app);4];5describe('GET /test', function() {6  it('should return 200', function(done) {7    request.get('/test')8      .expect(statusArray)9      .end(function(err, res) {10        if (err) return done(err);11        done();12      });13  });14});15var express = require('express');16var app = express();17app.get('/test', function(req, res) {18  res.status(200).send();19});20module.exports = app;Using AI Code Generation
1var request = require('supertest');2var _ = require('lodash');3var app = require('../app');4var _assertStatusArray = function (statusArray) {5    var self = this;6    var lastIndex = statusArray.length - 1;7    _.each(statusArray, function (status, index) {8        self.expect(status);9        if (index !== lastIndex) {10            self = self.expect('Content-Type', /json/);11        }12    });13};14describe('GET /', function () {15    it('respond with json', function (done) {16        request(app)17            .get('/')18            .expect('Content-Type', /json/)19            .expect(200)20            .end(function (err, res) {21                if (err) return done(err);22                done();23            });24    });25});26describe('GET /users', function () {27    it('respond with json', function (done) {28        request(app)29            .get('/users')30            .expect('Content-Type', /json/)31            .expect(200)32            .end(function (err, res) {33                if (err) return done(err);34                done();35            });36    });37});38describe('GET /users/:id', function () {39    it('respond with json', function (done) {40        request(app)41            .get('/users/1')42            .expect('Content-Type', /json/)43            .expect(200)44            .end(function (err, res) {45                if (err) return done(err);46                done();47            });48    });49});50describe('GET /users/:id', function () {51    it('respond with json', function (done) {52        request(app)53            .get('/users/2')54            .expect('Content-Type', /json/)55            .expect(200)56            .end(function (err, res) {57                if (err) return done(err);58                done();59            });60    });61});62describe('GET /users/:id', function () {63    it('respond with json', function (done) {64        request(app)65            .get('/users/3')66            .expect('Content-Type', /json/)67            .expect(200)68            .end(function (err, res) {69                if (err) return done(err);70                done();71            });72    });Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
