【问题标题】:How to write a test for an http request that checks the response's returned data?如何为检查响应返回数据的 http 请求编写测试?
【发布时间】:2015-06-30 10:40:05
【问题描述】:

我的AccountsApiHandler 模块中有以下方法,我想写一个测试是否正确返回帐户。如果我从我的一项测试中调用此方法,如何检索帐户列表?

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);
  }
};

这是我的测试,使用hammock npm 模块生成我的模拟请求和响应对象。此测试假定现有帐户已经在测试的数据库中: var test = require('tape') var吊床=需要('吊床') 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)
    })

}

当我运行这个测试时,我的accounts 流是空的,因此给了我一个空的accountsList 帐户列表。有没有一种不错的方法可以从我的 AccountsApiHandler.accounts 方法中获取帐户数据?

【问题讨论】:

    标签: node.js unit-testing http


    【解决方案1】:

    看起来我在上述问题中的实现很接近,但不是像这样流式传输accounts

      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)
        })
    
    }
    

    我需要流式传输响应本身,它也没有data 事件:

      accounts
        .on('end', function (err, data) {
          t.equals(data, actualAccounts)
        })
    

    希望这对某人有所帮助。更多文档在 npm 上的 hammock 站点中

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-30
      • 2014-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多