Javascript 在Mocha中使用请求调用测试函数

Javascript 在Mocha中使用请求调用测试函数,javascript,node.js,mocha.js,Javascript,Node.js,Mocha.js,我对node.js和摩卡非常陌生。我想测试以下功能: querybackend = function(url,queryParams) { var backendData ={}; request({url:url, qs:queryParams}, function(err, response, body) { if(err) { console.log(err); return; } var data = JSON.parse(body);

我对node.js和摩卡非常陌生。我想测试以下功能:

querybackend = function(url,queryParams) {
    var backendData ={};
    request({url:url, qs:queryParams}, function(err, response, body) {
        if(err) { console.log(err); return; }
        var data = JSON.parse(body);
        var length = data.length;
        var tmp = data[0].DataPoints[0].length;
        var in_sum =Array.apply(null, new Array(tmp)).map(Number.prototype.valueOf,0);
        var timestamp = [];
        var index1;
        var index2;
        for(index1=0;index1 < length;index1++) {
            var length2=data[index1].DataPoints.length;
            for(index2=0;index2<length2;index2++) {
                in_sum[index2]= in_sum[index2] + data[index1].DataPoints[index2][1];
                timestamp[index2] = data[index1].DataPoints[index2][0];
            }
        }
        backendData.count = in_sum;
        backendData.timestamp  = timestamp;
        deferred.resolve(backendData);
    });
    return deferred.promise;
};

我应该嘲笑这个请求吗?我如何在摩卡咖啡中模仿它

如果你想用摩卡创建模拟或存根,你需要使用一些模块。Sinon.js()是一个很好的工具,非常易于使用,并且文档记录良好

我认为您应该模拟请求函数来调用回调函数,并使用rest端点应该发送给您的答案


然后,您可以测试函数应该完成的所有操作是否都正确完成。顺便说一句,如果你想测试函数是否被调用,你可以用sinon在这个函数上创建一个间谍。

我发现用它来接收请求并返回API应该返回的任何内容更方便

通过这种方式,如果函数能够优雅地处理404或502之类的错误响应,那么您还可以在不同的测试用例中进行检查

简单的例子:

describe( 'querybackend', function () {

    it( 'should request the passed in URL', async function () {

        // Intercept requests to https://example.org/ and reply with HTTP 200 code 
        const scope = nock( 'https://example.org' )
            .get( '/' )
            .reply( 200 );

        // Call the function we are testing
        await querybackend( 'https://example.org/' );

        // Make sure the nock scope was properly called
        scope.done();

    } );

} );
我建议阅读nock文档,了解如何测试不同的请求和响应

describe( 'querybackend', function () {

    it( 'should request the passed in URL', async function () {

        // Intercept requests to https://example.org/ and reply with HTTP 200 code 
        const scope = nock( 'https://example.org' )
            .get( '/' )
            .reply( 200 );

        // Call the function we are testing
        await querybackend( 'https://example.org/' );

        // Make sure the nock scope was properly called
        scope.done();

    } );

} );