【问题标题】:request rest api and return response values for a mocha test请求 rest api 并返回 mocha 测试的响应值
【发布时间】:2018-02-09 13:02:30
【问题描述】:

在一个流星应用程序中,我想测试一些休息功能,因此我需要做一些身份验证。

在我的测试用例中,我想从函数中返回一些身份验证数据:

const supertest = require('supertest');

function loginUser(auth) {
  return function(done) {
    request
      .post('/users/login')
      .send({
        username: 'user'
        password: '123',
      })
      .expect(200)
      .end(onResponse);

    function onResponse(err, res) {
      auth.token = res.body.token;
      return done();
    }
  };
}

在这个测试中:

it('auth test by helper function', function () {
  let auth = {};
  auth = loginUser(auth)(done);
  //access auth settings here like:
  //auth.token
});

onResponse 永远不会被调用,auth 始终是 {}

我使用 supertest 请求 3.0.0 和 mocha 4.1.0 作为测试运行器(其余 api 很简单:json-routes)

更新

似乎从未调用过 return 'function(done)'...

好的,我已将电话固定到auth = loginUser(auth)(done);

现在通话已完成,但通话后 auth 未定义

【问题讨论】:

    标签: node.js rest mocha.js supertest


    【解决方案1】:

    您的 function loginUser(auth) 返回另一个函数。所以你也应该像这样调用那个函数:

    it('auth test by helper function', function (done) { // pass done so mocha knows it needs to wait for the response ...
      let auth = {};
      loginUser(auth)(function() {
         //access auth settings here like:
         //auth.token
         done();
      });       
    });
    

    【讨论】:

    • 我已更改代码以调用您的答案中的函数。呼叫已执行,但我认为摩卡咖啡没有等待。当我想访问令牌时,auth{}
    猜你喜欢
    • 2017-12-03
    • 1970-01-01
    • 2019-11-25
    • 2020-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-17
    • 1970-01-01
    相关资源
    最近更新 更多