在所有测试开始之前提出请求Mocha

时间:2018-05-29 13:55:32

标签: node.js api asynchronous mocha axios

我想测试一下有/groups网址的简单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()

1 个答案:

答案 0 :(得分:1)

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

至于在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);
        })
    });
});