我是前端开发人员,也是TDD和BDD的新手。
我有这个任务。使用从AJAX调用接收的json对象填充表。我如何在套件和规范中描述这个?
提前致谢
修改
我使用BackboneJS for MVC和sinon.js用于间谍,存根等。
答案 0 :(得分:2)
您没有提及很多关于您使用的库的内容,因此我将继续并假设您的ajax请求包含使用jQuery的GET请求。
通常情况如下:
$.ajax({
url: 'http://server/populate_table',
data: {foo: 'bar'},
success: populate_table
});
此外,我将假设服务器将返回以下对象{row: [1, 2, 3]}
对于初学者,您需要模拟ajax响应,因为您不希望依赖于您的服务器可用。可以通过使用 spy 来实现模拟,检查参数和虚假返回数据:
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]};
});
注意在调用带有结果的回调之前,如何定义服务器应该接收的url和数据的期望。
最后,您需要查看您的表格是否已填充。您没有提供有关数据或表的任何信息,但再次猜测您使用的是jQuery,您应该尝试jasmine-jquery。有了它,您可以轻松描述对DOM的期望,查看扩展文档。一旦确定了要测试的内容,您的完整测试将类似于:
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...
});
答案 1 :(得分:0)
答案 2 :(得分:0)
由于您已经在使用sinon.js,我认为最好的方法是使用fakeServer来测试从ajax调用接收的对象。这里有很好的描述(假Ajax和假服务器部分):
http://tinnedfruit.com/2011/03/03/testing-backbone-apps-with-jasmine-sinon.html