RAM
RAM

Reputation: 2759

How to check for plain text response from a POST request?

I'm trying to use frisby.js to specify an API test for an endpoint that returns a plain text response to a valid POST request. However I'm having problems getting frysby.js to accept non-JSON response documents. Whenever a response returns non-JSON content, throw a TypeError due to 'Unexpected token b in JSON at position 0'.

As an example, I'm sending a HTTP POST request with the JSON document shown below is expected to return a response with a plaintext document with the string bar.

{
    "foo":{
        "name":"bar"
    }
}

Here's the unit test that I've wrote to verify the response:

it('should create a foo resource', function () {
  return frisby.post('http://localhost:8080/', 
      {
        "foo":{
          "name":"bar"
        }
      })
    .expect('status',201);
});

Unfortunately, the following error is thrown by frisby.js when I run the test:

FAIL ./test.js ✕ should create a foo resource (17ms)

● should create a foo resource

TypeError: Invalid json response body: 'bar' at http://localhost:8080/ reason: 'Unexpected token b in JSON at position 0'

Does anyone know if it's possible to configure each test to expect some data format other than JSON?

Upvotes: 1

Views: 2613

Answers (1)

Avinash Singh
Avinash Singh

Reputation: 5392

If you getting JSON + something then break jsonTypes in two format like one for JSON object and one for other, like it having array in JSON objects. and then put expect conditions on them.

This might helps you:

const frisby = require('frisby');
const Joi = frisby.Joi;

frisby.globalSetup({
    headers : {
        "Accept": "application/json", 
        "content-type" : "application/json",
    }
});

it("should create a foo resource", function () {
    frisby.post("http://localhost:8080/")
        .expect("status", 200)
        .expect("header", "content-type", "application/json; charset=utf-8")
        .expect("jsonTypes", "data.foo", {
            "name": Joi.string()
        })
        .then(function(res) { // res = FrisbyResponse object
            var body = res.body;
            body = JSON.parse(body);

            expect(body.data.foo.name).toBeDefined();
        })
});

Upvotes: 0

Related Questions