1
votes

Thanks in advance for the help. I'm testing a GRAPHQL API using rest assured on testng in java.

I am trying to send agraphQL object disguised as JSON as a post, but when trying to package the string up as a JSON object I am getting the following error:

SyntaxError: Unexpected token B<br> &nbsp; &nbsp;at Object.parse (native)<br> &nbsp; &nbsp;at parse (/app/node_modules/body-parser/lib/types/json.js:88:17)<br> &nbsp; &nbsp;at /app/node_modules/body-parser/lib/read.js:116:18<br> &nbsp; &nbsp;at invokeCallback (/app/node_modules/raw-body/index.js:262:16)<br> &nbsp; &nbsp;at done (/app/node_modules/raw-body/index.js:251:7)<br> &nbsp; &nbsp;at IncomingMessage.onEnd (/app/node_modules/raw-body/index.js:307:7)<br> &nbsp; &nbsp;at emitNone (events.js:80:13)<br> &nbsp; &nbsp;at IncomingMessage.emit (events.js:179:7)<br> &nbsp; &nbsp;at endReadableNT (_stream_readable.js:913:12)<br> &nbsp; &nbsp;at _combinedTickCallback (internal/process/next_tick.js:74:11)<br> &nbsp; &nbsp;at process._tickDomainCallback (internal/process/next_tick.js:122:9)

The JSON object I am trying to create is here:

"{\"query\":\"{marketBySlug(slug: \"Boston\") {countryCode}}\"}"

I've figured out that my problem is the escaped quotes identifying Boston as a string are breaking the internally constructed Graphql query string, but I'm not sure how to get around this.

2

2 Answers

2
votes

Try this:

"{\"query\":\"{marketBySlug(slug: \\\"Boston\\\") {countryCode}}\"}"
1
votes

Instead of messing with strings and escaping, you should use parameterized queries. Your code will look like this:

String query =
        "query MarketBySlug($slug: String!) {\n" +
        "  marketBySlug(slug: $slug) {\n" +
        "    countryCode\n" +
        "  }\n" +
        "}";

    Map<String, Object> variables = new HashMap<>();
    variables.put("slug", slug);

    given()
    .body(new QueryDto(query, variables))
    .when()
    .post("/graphql")
    .then()
    .contentType(JSON)
    .statusCode(HttpStatus.OK.value())
    .body("data.marketBySlug.countryCode", equalTo(countryCode));

QueryDto is just a simple dto with the two fields (query and variables), setters and getters.