Skip to content

Instantly share code, notes, and snippets.

@gustavohenrique
Created June 13, 2018 13:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gustavohenrique/5cc3f8fdff44f5d358ed902ae10ec675 to your computer and use it in GitHub Desktop.
Save gustavohenrique/5cc3f8fdff44f5d358ed902ae10ec675 to your computer and use it in GitHub Desktop.
Test external API using NodeJS

setup

cat > package.json <<EOF
{
  "name": "test-api",
  "version": "0.1.0",
  "description": "It test the API",
  "main": "index.js",
  "scripts": {
    "test": "NODE_ENV=test npx mocha --recursive tests/**/*.spec.js"
  },
  "engines": {
    "node": ">=8.10.0",
    "npm": ">=6.0.1"
  },
  "author": "Gustavo Henrique",
  "private": true,
  "license": "UNLICENSED",
  "devDependencies": {
    "chai": "^4.1.2",
    "mocha": "^5.2.0",
    "mockdate": "^2.0.2",
    "supertest": "^3.1.0"
  }
}
EOF

npm install

testing

mkdir -p tests/users
cat > tests/users/index.spec.js <<EOF
var expect = require('chai').expect;
var request = require('supertest');
var DatabaseHelper = require('../helpers').DatabaseHelper;

describe('users', function () {

  var httpClient = null;
  var db = null;

  before(function () {
    // DatabaseHelper eh usado para executar queries de arquivos .sql
    db = new DatabaseHelper();
  });

  beforeEach(function (done) {
    var schemas = 'test/sql/databases.sql';
    var table = 'test/sql/users.sql';
    db.executeFile(schemas)
      .then(function () {
        return db.executeFile(table);
      })
      .then(function () {
        httpClient = request('https://api.mycompany.com');
        done();
      })
      .catch(function (err) {
        console.log(err.message);
        done();
      });
  });

  describe('/users', function () {

    it('should fail when email is invalid', function (done) {
      var req = {
        email: 'aaaaa',
        password: '123456'
      };
      httpClient.post('/users')
        .set('Accept', 'application/json')
        .send(req)
        .end(function (err, res) {
          if (err) { throw err; }
          expect(res.status).to.equal(400);
          expect(res.body).to.have.property('error');
          done();
        });
    });

    it('should retrieve all users', function (done) {
      httpClient.get('/users')
        .set('Accept', 'application/json')
        .end(function (err, res) {
          if (err) { throw err; }
          expect(res.status).to.equal(200);
          expect(res.body.length).to.equal(10);
          var firstUser = res.body[0];
          expect(firstUser.id).to.equal(1);
          expect(firstUser.email).to.equal('user@host.com');
          done();
        });
    });
  });
});
EOF

running

npm test
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment