我想测试一下有/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()
?
答案 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);
})
});
});