Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assert/unit-test servers JSON response?

My current project uses JSON as data interchange format. Both Front-end and Back-end team agree upon a JSON structure before start integrating a service. At times due to un-notified changes in JSON structure by back-end team; it breaks the front-end code.

Is there any external library that we could use to compare a mock JSON (fixture) with servers JSON response. Basically it should assert the whole JSON object and should throw an error if there is any violation in servers JSON format.

Additional info: App is built on JQuery consuming REST JSON services.

like image 342
shazmoh Avatar asked Mar 24 '10 03:03

shazmoh


3 Answers

I would recommend a schema for your JSON objects.

I use Kwalify but you can also use Rx if you like that syntax better.

like image 129
Paul Tarjan Avatar answered Sep 22 '22 16:09

Paul Tarjan


I've been using QUnit: http://docs.jquery.com/QUnit recently for a lot of my JS code.

asyncTest http://docs.jquery.com/QUnit/asyncTest could be used pretty effectively to test JSON Structure.

Example:


asyncTest("Test JSON API 1", 1, function() {
    $.getJSON("http://test.com/json", function(data) {
        equals(data.expected, "what you expected", "Found it");
    });
});
like image 44
William Avatar answered Sep 20 '22 16:09

William


Looks like you're trying to solve a problem from other end. Why should you as a front-end developer bother with testing back-end developer's work?

A JSON that is generated on server is better to test on server using standard approach, i.e. functional tests in xUnit. You could also look at acceptance test frameworks like FITnesse if you want to have tests and documentation wiki all in one.

If even after introducing testing on server you'll get invalid JSON it is a problem in human communication, not in tests.

like image 43
nkrkv Avatar answered Sep 22 '22 16:09

nkrkv