{"id":13414779,"url":"https://github.com/ladjs/supertest","last_synced_at":"2025-05-12T18:12:46.193Z","repository":{"id":37432067,"uuid":"4813464","full_name":"ladjs/supertest","owner":"ladjs","description":"🕷 Super-agent driven library for testing node.js HTTP servers using a fluent API.   Maintained for @forwardemail, @ladjs, @spamscanner, @breejs, @cabinjs, and @lassjs.","archived":false,"fork":false,"pushed_at":"2025-03-20T15:48:09.000Z","size":794,"stargazers_count":13999,"open_issues_count":182,"forks_count":765,"subscribers_count":114,"default_branch":"master","last_synced_at":"2025-04-23T21:41:59.896Z","etag":null,"topics":["assertions","node","superagent","supertest"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ladjs.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2012-06-27T20:56:12.000Z","updated_at":"2025-04-23T19:05:22.000Z","dependencies_parsed_at":"2024-09-20T16:11:55.637Z","dependency_job_id":"98c6614d-a2da-49f8-85da-baa46f30bf19","html_url":"https://github.com/ladjs/supertest","commit_stats":{"total_commits":355,"total_committers":96,"mean_commits":"3.6979166666666665","dds":0.8140845070422535,"last_synced_commit":"fd571c82cdce1a7ba93f9a576277dbe535fd381f"},"previous_names":["visionmedia/supertest"],"tags_count":67,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ladjs%2Fsupertest","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ladjs%2Fsupertest/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ladjs%2Fsupertest/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ladjs%2Fsupertest/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ladjs","download_url":"https://codeload.github.com/ladjs/supertest/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":252522432,"owners_count":21761729,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["assertions","node","superagent","supertest"],"created_at":"2024-07-30T21:00:36.538Z","updated_at":"2025-05-05T15:23:16.901Z","avatar_url":"https://github.com/ladjs.png","language":"JavaScript","readme":"# [SuperTest](https://ladjs.github.io/superagent/)\n\n[![code coverage][coverage-badge]][coverage]\n[![Build Status][travis-badge]][travis]\n[![Dependencies][dependencies-badge]][dependencies]\n[![PRs Welcome][prs-badge]][prs]\n[![MIT License][license-badge]][license]\n\n\u003e HTTP assertions made easy via [superagent](http://github.com/ladjs/superagent).  Maintained for [Forward Email](https://github.com/forwardemail) and [Lad](https://github.com/ladjs).\n\n## About\n\nThe motivation with this module is to provide a high-level abstraction for testing\nHTTP, while still allowing you to drop down to the [lower-level API](https://ladjs.github.io/superagent/) provided by superagent.\n\n## Getting Started\n\nInstall SuperTest as an npm module and save it to your package.json file as a development dependency:\n\n```bash\nnpm install supertest --save-dev\n```\n\n  Once installed it can now be referenced by simply calling ```require('supertest');```\n\n## Example\n\nYou may pass an `http.Server`, or a `Function` to `request()` - if the server is not\nalready listening for connections then it is bound to an ephemeral port for you so\nthere is no need to keep track of ports.\n\nSuperTest works with any test framework, here is an example without using any\ntest framework at all:\n\n```js\nconst request = require('supertest');\nconst express = require('express');\n\nconst app = express();\n\napp.get('/user', function(req, res) {\n  res.status(200).json({ name: 'john' });\n});\n\nrequest(app)\n  .get('/user')\n  .expect('Content-Type', /json/)\n  .expect('Content-Length', '15')\n  .expect(200)\n  .end(function(err, res) {\n    if (err) throw err;\n  });\n```\n\nTo enable http2 protocol, simply append an options to `request` or `request.agent`:\n\n```js\nconst request = require('supertest');\nconst express = require('express');\n\nconst app = express();\n\napp.get('/user', function(req, res) {\n  res.status(200).json({ name: 'john' });\n});\n\nrequest(app, { http2: true })\n  .get('/user')\n  .expect('Content-Type', /json/)\n  .expect('Content-Length', '15')\n  .expect(200)\n  .end(function(err, res) {\n    if (err) throw err;\n  });\n\nrequest.agent(app, { http2: true })\n  .get('/user')\n  .expect('Content-Type', /json/)\n  .expect('Content-Length', '15')\n  .expect(200)\n  .end(function(err, res) {\n    if (err) throw err;\n  });\n```\n\nHere's an example with mocha, note how you can pass `done` straight to any of the `.expect()` calls:\n\n```js\ndescribe('GET /user', function() {\n  it('responds with json', function(done) {\n    request(app)\n      .get('/user')\n      .set('Accept', 'application/json')\n      .expect('Content-Type', /json/)\n      .expect(200, done);\n  });\n});\n```\n\nYou can use `auth` method to pass HTTP username and password in the same way as in the [superagent](http://ladjs.github.io/superagent/#authentication):\n\n```js\ndescribe('GET /user', function() {\n  it('responds with json', function(done) {\n    request(app)\n      .get('/user')\n      .auth('username', 'password')\n      .set('Accept', 'application/json')\n      .expect('Content-Type', /json/)\n      .expect(200, done);\n  });\n});\n```\n\nOne thing to note with the above statement is that superagent now sends any HTTP\nerror (anything other than a 2XX response code) to the callback as the first argument if\nyou do not add a status code expect (i.e. `.expect(302)`).\n\nIf you are using the `.end()` method `.expect()` assertions that fail will\nnot throw - they will return the assertion as an error to the `.end()` callback. In\norder to fail the test case, you will need to rethrow or pass `err` to `done()`, as follows:\n\n```js\ndescribe('POST /users', function() {\n  it('responds with json', function(done) {\n    request(app)\n      .post('/users')\n      .send({name: 'john'})\n      .set('Accept', 'application/json')\n      .expect('Content-Type', /json/)\n      .expect(200)\n      .end(function(err, res) {\n        if (err) return done(err);\n        return done();\n      });\n  });\n});\n```\n\nYou can also use promises:\n\n```js\ndescribe('GET /users', function() {\n  it('responds with json', function() {\n    return request(app)\n      .get('/users')\n      .set('Accept', 'application/json')\n      .expect('Content-Type', /json/)\n      .expect(200)\n      .then(response =\u003e {\n         expect(response.body.email).toEqual('foo@bar.com');\n      })\n  });\n});\n```\n\nOr async/await syntax:\n\n```js\ndescribe('GET /users', function() {\n  it('responds with json', async function() {\n    const response = await request(app)\n      .get('/users')\n      .set('Accept', 'application/json')\n    expect(response.headers[\"Content-Type\"]).toMatch(/json/);\n    expect(response.status).toEqual(200);\n    expect(response.body.email).toEqual('foo@bar.com');\n  });\n});\n```\n\nExpectations are run in the order of definition. This characteristic can be used\nto modify the response body or headers before executing an assertion.\n\n```js\ndescribe('POST /user', function() {\n  it('user.name should be an case-insensitive match for \"john\"', function(done) {\n    request(app)\n      .post('/user')\n      .send('name=john') // x-www-form-urlencoded upload\n      .set('Accept', 'application/json')\n      .expect(function(res) {\n        res.body.id = 'some fixed id';\n        res.body.name = res.body.name.toLowerCase();\n      })\n      .expect(200, {\n        id: 'some fixed id',\n        name: 'john'\n      }, done);\n  });\n});\n```\n\nAnything you can do with superagent, you can do with supertest - for example multipart file uploads!\n\n```js\nrequest(app)\n  .post('/')\n  .field('name', 'my awesome avatar')\n  .field('complex_object', '{\"attribute\": \"value\"}', {contentType: 'application/json'})\n  .attach('avatar', 'test/fixtures/avatar.jpg')\n  ...\n```\n\nPassing the app or url each time is not necessary, if you're testing\nthe same host you may simply re-assign the request variable with the\ninitialization app or url, a new `Test` is created per `request.VERB()` call.\n\n```js\nrequest = request('http://localhost:5555');\n\nrequest.get('/').expect(200, function(err){\n  console.log(err);\n});\n\nrequest.get('/').expect('heya', function(err){\n  console.log(err);\n});\n```\n\nHere's an example with mocha that shows how to persist a request and its cookies:\n\n```js\nconst request = require('supertest');\nconst should = require('should');\nconst express = require('express');\nconst cookieParser = require('cookie-parser');\n\ndescribe('request.agent(app)', function() {\n  const app = express();\n  app.use(cookieParser());\n\n  app.get('/', function(req, res) {\n    res.cookie('cookie', 'hey');\n    res.send();\n  });\n\n  app.get('/return', function(req, res) {\n    if (req.cookies.cookie) res.send(req.cookies.cookie);\n    else res.send(':(')\n  });\n\n  const agent = request.agent(app);\n\n  it('should save cookies', function(done) {\n    agent\n    .get('/')\n    .expect('set-cookie', 'cookie=hey; Path=/', done);\n  });\n\n  it('should send cookies', function(done) {\n    agent\n    .get('/return')\n    .expect('hey', done);\n  });\n});\n```\n\nThere is another example that is introduced by the file [agency.js](https://github.com/ladjs/superagent/blob/master/test/node/agency.js)\n\nHere is an example where 2 cookies are set on the request.\n\n```js\nagent(app)\n  .get('/api/content')\n  .set('Cookie', ['nameOne=valueOne;nameTwo=valueTwo'])\n  .send()\n  .expect(200)\n  .end((err, res) =\u003e {\n    if (err) {\n      return done(err);\n    }\n    expect(res.text).to.be.equal('hey');\n    return done();\n  });\n```\n\n## API\n\nYou may use any [superagent](http://github.com/ladjs/superagent) methods,\nincluding `.write()`, `.pipe()` etc and perform assertions in the `.end()` callback\nfor lower-level needs.\n\n### .expect(status[, fn])\n\nAssert response `status` code.\n\n### .expect(status, body[, fn])\n\nAssert response `status` code and `body`.\n\n### .expect(body[, fn])\n\nAssert response `body` text with a string, regular expression, or\nparsed body object.\n\n### .expect(field, value[, fn])\n\nAssert header `field` `value` with a string or regular expression.\n\n### .expect(function(res) {})\n\nPass a custom assertion function. It'll be given the response object to check. If the check fails, throw an error.\n\n```js\nrequest(app)\n  .get('/')\n  .expect(hasPreviousAndNextKeys)\n  .end(done);\n\nfunction hasPreviousAndNextKeys(res) {\n  if (!('next' in res.body)) throw new Error(\"missing next key\");\n  if (!('prev' in res.body)) throw new Error(\"missing prev key\");\n}\n```\n\n### .end(fn)\n\nPerform the request and invoke `fn(err, res)`.\n\n## Notes\n\nInspired by [api-easy](https://github.com/flatiron/api-easy) minus vows coupling.\n\n## License\n\nMIT\n\n[coverage-badge]: https://img.shields.io/codecov/c/github/ladjs/supertest.svg\n[coverage]: https://codecov.io/gh/ladjs/supertest\n[travis-badge]: https://travis-ci.org/ladjs/supertest.svg?branch=master\n[travis]: https://travis-ci.org/ladjs/supertest\n[dependencies-badge]: https://david-dm.org/ladjs/supertest/status.svg\n[dependencies]: https://david-dm.org/ladjs/supertest\n[prs-badge]: https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square\n[prs]: http://makeapullrequest.com\n[license-badge]: https://img.shields.io/badge/license-MIT-blue.svg?style=flat-square\n[license]: https://github.com/ladjs/supertest/blob/master/LICENSE\n","funding_links":[],"categories":["JavaScript","An Node JS supercool REST API","node"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fladjs%2Fsupertest","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fladjs%2Fsupertest","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fladjs%2Fsupertest/lists"}