bbyars / mountebank

Over the wire test doubles
http://www.mbtest.org
MIT License
2k stars 268 forks source link

Inject JS : Issue #309

Closed vijay-nts closed 6 years ago

vijay-nts commented 7 years ago

Expected behaviour

Should return status code, headers and body : response ...

Actual behaviour

Keeps on Loading and not returning the values ...

Steps to reproduce

"responses": [ { "inject": "<%-stringify(filename, './GetProductInfo.js') %>" }

],

"predicates": [ { "matches": { "method" : "POST", "path" : "/details/search" } } ]

GetProductInfo.js function GetTemplateResponse (request, state, logger)

{ var productId; var response = JSON.parse("<%- stringify(filename, './es_productinfo.json') %>"); getUpdatedCSVData(function(data) { console.log('callback data >>>>>>>>: ', data);
// Process data and update response and return return {
statusCode : 200, headers: { 'Content-Type': 'application/json; charset=utf-8' }, body: response };

    });

    function getUpdatedCSVData(callback) 
        {
            console.log('getUpdatedCSVData......');
            var csv = require("fast-csv");
            csv.fromPath("dataset.csv")
            .on("data", function(data){
            //console.log(data);
            callback(data);
        })
        .on("end", function()
            {
                console.log("done");
            });
}

console.log('callback data 2: ', data);

}


If return is given outside getUpdatedCSVData(function(data) function as below it is working but not able update the response from CSV data and it is giving default value. Also if we try to update outside getUpdatedCSVData function it is not happening as this statement is processed before getting data from csv as it is running asynchronously.

function GetTemplateResponse (request, state, logger) 

{ var productId; var data; var sleep = require('sleep'); var response = JSON.parse("<%- stringify(filename, './es_productinfo.json') %>");

getUpdatedCSVData(function(data) 

    {
        console.log('callback data >>>>>>>>: ', data);

        // Process data and update respnse and return

    });

return {

            statusCode : 200,
            headers: {
                'Content-Type': 'application/json; charset=utf-8'
            },
            body: response
        };

    function getUpdatedCSVData(callback) 
        {
            console.log('getUpdatedCSVData......');
            var csv = require("fast-csv");
            csv.fromPath("/Users/vijayakumar_k/Documents/CSVtoJSON/dataset.csv")
            .on("data", function(data){
            //console.log(data);
            callback(data);
        })
        .on("end", function()
            {
                console.log("done");
            });
}

console.log('callback data 2: ', data);

}

........

Software versions used

OS         : MAC - 10.12
mountebank :  v1.13.0 
node.js    :v6.11.1
  (only if installed via npm)
Installation method : npm
  (npm, zip, tar, pkg, deb, rpm)

Log contents in mb.log when running mb --loglevel debug

debug: [http:4547] ::1:63018 ESTABLISHED
debug: [http:4547] ::1:63019 ESTABLISHED
debug: [http:4547] ::1:63018 LAST-ACK
debug: [http:4547] ::1:63018 CLOSED
info: [http:4547] ::1:63019 => POST /productdetails/_search
debug: [http:4547] ::1:63019 => {"requestFrom":"::1:63019","method":"POST","path":"/productdetails/_search","query":{},"headers":{"cache-control":"no-cache","Postman-Token":"260eaf9a-2e1b-4825-9198-536d822f84a7","User-Agent":"PostmanRuntime/6.2.5","Accept":"*/*","Host":"localhost:4547","accept-encoding":"gzip, deflate","content-length":"0","Connection":"keep-alive"},"body":""}
debug: [http:4547] ::1:63019 using predicate match: [{"matches":{"method":"POST","path":"/productdetails/_search"}}]
bbyars commented 6 years ago

Hi there, The problem is that your injection function requires asynchronicity, which means you need to supply a callback parameter to it instead of returning out of it. See http://www.mbtest.org/docs/api/injection for an example (search for "asynchronous" on the page to find the example).

The injection function's signature should be:

function GetTemplateResponse (request, state, logger,  callback) 

And then when you get your results from the CSV parsing, pass them to callback rather than returning.