lundi 29 juin 2015

How to write a test for an http request that checks the responses returned data?

I have the following method in my AccountsApiHandler module, and I would like write a test that ensures that the accounts are correctly returned. If I am calling this method from one of my tests, how can I retrieve the list of accounts?

AccountsApiHandler.prototype.accounts = function (req, res) {
  var self = this

  /*
   *  Get list of accounts
   */

  if (req.method === 'GET') {
    return self.server.accounts.listAccountAsJson()
      .pipe(JSONStream.stringify())
      .pipe(res);
  }
};

Here is my test, using the hammock npm module to generate my mock request and response objects. This test assumes that the existing accounts are already in the test's database: var test = require('tape') var hammock = require('hammock') var accountsApiHandler = require('../../handlers/accounts-api')()

test('create initial accounts', function (t) {
  request = hammock.Request({
    method: 'GET',
    headers: {
      'content-type': 'application/json'
    },
    url: '/somewhere'
  })
  request.method = 'GET'
  request.end()

  response = hammock.Response()
  var accounts = accountsApiHandler.accounts(request, response)
  console.log("test.accountsApiHandler: accountsApiHandler.accounts: accounts", accounts) // `accounts` is undefined!

  var accountsList = []
  var actualAccounts = getAccountsFromDatabase() // the actual accounts from our db
  accounts
    .on('data', function (data) {
      accountsList.push(data)
    })
    .on('error', function (err) {
      t.fail(err)
    })
    .on('end', function () {
      console.log("results:", accountsList)
      t.equals(accountsList, actualAccounts)
    })

}

When I run this test, my accounts stream is empty, thus giving me an empty list of accounts for accoutnsList. Is there a clean way to get the accounts from my AccountsApiHandler.accounts method?

Aucun commentaire:

Enregistrer un commentaire