代码之家  ›  专栏  ›  技术社区  ›  Greg Wozniak

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

  •  0
  • Greg Wozniak  · 技术社区  · 8 年前

    我想测试我的简单API /groups 网址。 我想在所有测试开始之前向该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();
             })      
        });
    

    但也没有运气。

    我得到的错误就是 响应 没有变化,也不可见 it . 断言错误:期望具有属性“length”

    总结: 我怎么通过 响应 从AXIOS内部到 in() ?

    1 回复  |  直到 8 年前
        1
  •  1
  •   sripberger    8 年前

    你的第一个表格是错误的,因为你没有返回被束缚的承诺。因此,摩卡不知道什么时候 before 完成了,甚至它是异步的。你的第二种形式可以解决这个问题,但是自从 axios.get 已经兑现了承诺,不使用摩卡内置的承诺支持是一种浪费。

    使响应在 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);
            })
        });
    });