【问题标题】:How to test callback of function in Chai?如何在 Chai 中测试函数的回调?
【发布时间】:2018-11-29 17:24:54
【问题描述】:

我正在使用 Slack API,我想测试它是否可以与响应状态代码一起正常工作。这是发送功能:

    sendMsg(msg) {
      return this.slack.webhook({text: msg}, (err, res) => {
        if (err) {
            throw err;
        }
        console.log(res.statusCode) // = 200
        return res.statusCode;
      });
    }

我的测试:

    it('Checks connection with Slack', (() => {
      let slack = new Slack();
      let res = slack.sendMsg('test');
      expect(res).to.equal(200);
    }));

但是ofc。它让我请求对象松弛。我想等待来自 slack API 的响应对象。提前致谢。

【问题讨论】:

  • sendMsg 函数是否返回一个承诺?如果没有,我认为它需要自己的回调。
  • Idk,它是 slack 的第 3 方库。 :(
  • 您可能应该查看 slack API 返回的内容,因为您将其返回给sendMsg 的调用者。你的sendMsg 函数写得有点像它从slack.webhook 返回一个承诺,但它也使用回调。我认为sendMsg 的调用者永远不会得到结果。
  • Slack API 返回带有状态码等的响应对象。我想在测试中抓取它。 sendMsg 是我 100% 的功能。

标签: javascript unit-testing mocha.js bdd chai


【解决方案1】:

看起来slack.webhook 接受了回调,这是您检索状态的方式。问题是sendMsg 的调用者无法获得该状态。

解决此问题的一种方法是让sendMsg 接受回调:

sendMsg(msg, onStatusReceived) {
  this.slack.webhook({text: msg}, (err, res) => {
    if (err) {
        throw err;
    }
    console.log(res.statusCode) // = 200
    onStatusReceived(res.statusCode);
  });
}

然后在你的测试中,调用回调时使用done结束测试:

it('Checks connection with Slack', (done) => {
  let slack = new Slack();
  slack.sendMsg('message', status => {
    expect(status).to.equal(200);
    done();
  });
});

另一种方法是让sendMsgslack.webhook 包装在一个promise 中,这样调用者就可以执行sendMsg().then(...)

【讨论】:

  • 我复制粘贴你的代码,它抛出Uncaught TypeError: onStatusReceived is not a function 这显然不是函数而是参数。
  • 它在测试中抛出那个错误?还是在您的实际代码中?任何调用sendMsg 的代码现在都需要传入一个回调来检索状态。
  • 测试期间。在正常请求中,它很好。我稍微编辑了我的代码,函数在现实生活中需要一些文本。
  • 更新了我的例子
  • @bdddd 您还应该使用回调将任何错误传递给调用代码,而不是抛出错误。如果该特定的松弛 webhook(或任何它是)失败,则抛出会导致进程崩溃的危险。见Error-first callbacks
【解决方案2】:

我处理返回回调到测试的方法之一如下:

it('receives successful response', async () => { 

nock('https://localhost')
            .persist()
            .log(console.log)
            .post(‘/getData’, (unitData, callback) => {
                return true;
            })
            .delayBody(1000)
            .reply(200, {statusCode: 'Some Status'});

const getSomeData = await getResponse(unitData, function callBack(unitData, error, data){
     expect(data.statusCode).to.be.equal(200); 
}) })

getResponse 函数(返回回调):

getResponse(unitData, function callBack(unitData, error, data){ 
   try {
    return request.post(unitData, function (err, resp) {
        if (!err && resp.statusCode === 200) {
            if (resp.body.error) {
                return callback(obj, JSON.stringify(resp.body.error), null); 
            }
            return callback(obj, null, resp); 
        } else {
            if (err == null) {  
                err = { statusCode: resp.statusCode, error: 'Error occured.' };
            }
            return callback(obj, err, null); 
        }
    });
} catch (err) {
    return callback(obj, err, null);
}
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-25
    • 2022-12-06
    • 1970-01-01
    • 2015-03-06
    • 1970-01-01
    • 2016-12-18
    • 2015-06-02
    相关资源
    最近更新 更多