Mocha/Chai http get 请求问题

Mocha/Chai issue with http get request

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

这是我正在尝试的测试 运行:

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 进行期望,它 returns "Cannot read property 'body' of undefined"。但是 console.log 有效。

A 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}

怎么样:

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

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

您需要将 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();
    });
});