使用http获取请求的Mocha / Chai问题

时间:2017-07-06 15:20:22

标签: javascript mocha chai

我在chai测试中遇到了http响应问题,我不知道如何通过console.log来获取res.body的长度。

这是我试图运行的测试:

it('It should have a length of 3061', function(){

        chai.request('http://localhost:8080')
        .get('/api/pac/')
        .end(function(err,res){

            console.log(res.body.length); //it shows 3061
            expect(res.body).to.have.lengthOf(3061); //it causes error "Cannot read property 'body' of undefined"

        });
    });

如果我尝试用res.body做一个期望,它会返回“无法读取未定义的属性'主体'”。但是console.log工作正常。

console.log(res.body)显示一个包含3061个对象的json。每个对象都有这种结构:

iid : {type : Number},

dnas : [{ _id : Number, 
        col : Date, 
        reproved : {type : Boolean},
        wave : {type: Number, 
                index: true}
        }],
name : { type : String,
       uppercase: true,
       index: true}

2 个答案:

答案 0 :(得分:3)

您需要将done传递给it回调,因为chai.request('http://localhost:8080').get()是异步的。没有它,你会在it完成后尝试运行断言。换句话说,您需要告诉it等待HTTP get请求完成。注意,我使用了一些es6。如果您的项目不支持es6,请用回调函数替换我的箭头。

it('should have a length of 3061', done => {
    chai.request('http://localhost:8080')
    .get('/api/pac/')
    .end((err, res) => {
        if (err) done(err);

        expect(res.body).to.have.lengthOf(3061);
        done();
    });
});

答案 1 :(得分:0)

怎么样:

expect(res.body.length).to.equal(3061);

可以记住它是.equal还是.be,但其中一个应该有效。