Reputation: 19822
I am front end developer and new to TDD and BDD.
I have this task. Populate a table with json object received from an AJAX call. How would I describe this in a suite and spec?
Thanks in advance
EDIT
I am using BackboneJS for MVC and sinon.js for spies, stubs etc.
Upvotes: 4
Views: 1435
Reputation: 404
Since you are already using sinon.js, I think the best approach would be using fakeServer for testing objects received from ajax calls. It is very well described here (Fake Ajax and fake servers section):
http://tinnedfruit.com/2011/03/03/testing-backbone-apps-with-jasmine-sinon.html
Upvotes: 0
Reputation: 13105
You don't mention a lot about what libraries you use, so I will just go ahead and assume for the sake of example your ajax request consists of a GET request using jQuery.
Normally this would be something like:
$.ajax({
url: 'http://server/populate_table',
data: {foo: 'bar'},
success: populate_table
});
Also I will assume that the server would return the following object {row: [1, 2, 3]}
For starters you need to mock the ajax response since you don't want to be relying on your server being available. The mocking, checking of parameters and fake return of the data can be achieved by using a spy as such:
var ajaxMock = spyOn($, 'ajax').andCallFake(function (options) {
expect(options.url).toEqual('http://server/populate_table');
expect(options.data.foo).toEqual('bar');
options.success({row: [1, 2, 3]};
});
Notice how above you define expectations about the url and data that should be received by the server before calling the callback with the result.
Finally, you need to see whether your table was populated. You don't provide any info on the data or the table, but again guessing that you use jQuery, you should give a try to jasmine-jquery. With it you can easily describe expectations on your DOM, have a look at the extended docs. Once you settle on what you want to test, your full test will look similar to:
it('populates the table making a JSON call', function () {
var ajaxMock = spyOn($, 'ajax').andCallFake(function (options) {
expect(options.url).toEqual('http://server/populate_table');
expect(options.data.foo).toEqual('bar');
options.success({row: [1, 2, 3]};
});
$.ajax({
url: 'http://server/populate_table',
data: {foo: 'bar'},
success: populate_table
});
expect($('#mytable')).toExist();
// DOM specific expectations go here...
});
Upvotes: 2
Reputation: 22758
You want to look at the asynchronous test facilities built into jasmine.
Specifically waitFor
and run
.
To explain quickly: you can run an Ajax query and have it return true on success. You wait for that function and then run your test.
Upvotes: 0