【问题标题】:Making a request before all tests start in Mocha在 Mocha 开始所有测试之前发出请求
【发布时间】:2018-11-08 05:11:30
【问题描述】:

我想测试具有/groups URL 的简单API。 我想在所有测试开始之前向该 URL 发出 API 请求(使用 Axios),并使响应对所有测试函数可见。

我正在尝试使 response 可见但无法使其工作。我关注了一个类似的案例with filling out the DB upfront,但我的案例没有运气。

下面是我的简单测试文件:

var expect  = require('chai').expect
var axios = require('axios')
var response = {};
describe('Categories', function() {    
    describe('Groups', function() {
        before(function() {
            axios.get(config.hostname + '/groups').then(function (response) {                                                            
                return response;
            })                
        });

        it('returns a not empty set of results', function(done) {
            expect(response).to.have.length.greaterThan(0);
            done();            
        })
    });    
});

我还尝试了对before 函数的轻微修改:

before(function(done) {
    axios.get(config.hostname + '/groups')
         .then(function (response) {                                                            
             return response;
         }).then(function() {
             done();
         })      
    });

但也没有运气。

我得到的错误只是response 没有改变,也没有在it 中可见。 AssertionError:期望 {} 具有属性“长度”

总结:如何将response从axios内部传递给in()

【问题讨论】:

    标签: node.js api asynchronous mocha.js axios


    【解决方案1】:

    您的第一个表单不正确,因为您没有返回链式承诺。因此,mocha 无法知道您的 before 何时完成,甚至根本无法知道它是异步的。你的第二种形式可以解决这个问题,但是由于axios.get已经返回了一个promise,不使用mocha内置的promise支持有点浪费。

    至于使响应在it 中可见,您需要将其分配给在it 中可见的范围内的变量。

    var expect  = require('chai').expect
    var axios = require('axios')
    var response;
    describe('Categories', function() {
        describe('Groups', function() {
            before(function() {
                // Note that I'm returning the chained promise here, as discussed.
                return axios.get(config.hostname + '/groups').then(function (res) {
                    // Here's the assignment you need.
                    response = res;
                })
            });
    
            // This test does not need the `done` because it is not asynchronous.
            // It will not run until the promise returned in `before` resolves.
            it('returns a not empty set of results', function() {
                expect(response).to.have.length.greaterThan(0);
            })
        });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-07
      • 2012-05-26
      • 2016-11-08
      相关资源
      最近更新 更多