Thursday, 8 June 2017

Mock api stream output in nodejs

I am trying to mock external API output which comes as stream(chunk) in xml which i am parsing. I am trying to write unit test to mock API and send mocked data but its not working with NOCK which i am using for API mocking.

Any help is appreciated. Any other framework apart from NOCK is also welcome.

    var request = require('superagent');
var xml2js = require('xml2js');
var parser = new xml2js.Parser();

var getMyData = function(callback) {
  parser.on('error', function(err) {
     console.log('Parser error', err);
     callback('Error Occurred!'+err);
  });

 var data = '';
  request    
    .get(`https://myapp.com`)    
    .end(function(err, res) {      
      if (res.statusCode >= 200 && res.statusCode < 400) {        
        res.on('data', function(data_) {
          //console.log('--------------------------');
          data += data_.toString();
        });        
        var datainjson = '';
        res.on('end', function() {          
          parser.parseString(data, function(err, result) {            
            if(!err){
              datainjson = JSON.stringify(result);
            }else{
              datainjson = 'Error Occurred!'+err;
            }
          });
          callback(err, datainjson);
        });
      }
  });
};
module.exports.getMyData = getMyData;


    var should = require('chai').should();
var expect = require('chai').expect;
var nock = require('nock');
var fs = require('fs');
var getMyData = require('./index4').getMyData;

describe('test mock', function() {

  beforeEach(function() {        
    // Mock the TMDB configuration request response
    nock('https://myapp.com')
      .get('')
      .reply(200, function (req, res) {        
            var stream = fs.createReadStream('a.txt');
            stream.pipe(res);                
        });
  });

  it('should have data', function(done) {
    this.timeout(3000);
    getMyData(function(err, testdata) {
      var x = JSON.parse(testdata);      
      });
      done();
    });
  });

});



via devashish

No comments:

Post a Comment