sharkbait sharkbait - 1 year ago 206
Node.js Question

Translate an API in a chai request

I have this call to an API:


curl -X PATCH --header 'Content-Type: application/json' --header 'Authorization: Bearer 863e2ddf246300f6c62ea9023d068805' -d '1' 'http://asdasd.com/api/loyalty/v1/Accounts/6064361727001553966/Cards'


and I want to write a chai request to test my API.
I wrote this:

describe('/PATCH Patch a card with a Status variable inactive test', () => {


it('it should GET a sample error json response ', (done) => {
chai.request(app)
.patch('/loyalty/v1/cards/6064361727001553966')
.send({"cardStatus": "1" })
.end((err, res) => {
res.should.have.status(200);
done();
});
});
});


but in this way I pass the "1" value like value of the cardStatus parameter. In the API call I have only this


-d '1'


How can I reproduce this in the chai request?
There is a way to pass this parameter in the request body without a parameter key?

Answer Source

I found a solution. I added this to my .js file:

app.use(function(req, res, next){
  if (req.is('text/*')) {
    req.text = '';
    req.setEncoding('utf8');
    req.on('data', function(chunk){ req.text += chunk });
    req.on('end', next);
  } else {
    next();
  }
});

and used req.text to get the string from the request.

The chai request is written now like this:

describe('/PATCH Patch a card with a Status variable active test', () => {
  it('it should GET a sample error json response ', (done) => {
  chai.request(app)
    .post('/loyalty/v1/cards/6064361727001553966')
    .set('content-type', 'text/plain')
    .send('1')
    .end((err, res) => {
    res.should.have.status(200);
  done();
});
});
});

and I can call my api in the command line like this:

curl -v -X POST --header 'Content-Type: text/plain' -d '1' 'https://asdasd.com/api/loyalty/v1/cards/6064361727001553966'

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download