我有一个基本的jQuery帖子到一个网址,我想测试它。我已经做了Sinon创建服务器测试,但我也想测试方法中给出的url和属性,但是我得到了错误,因为jQuery.post(url, data).always(callback)
无法在未定义的对象上调用。
还有什么我应该测试?
这是我的jQuery代码。
define(['jquery'], function (jQuery) {
var ProductListingService = function () {
var self = this;
self.create = function (sku, quantity, price, callback) {
var url = '/url';
var data = { 'sku': sku, 'quantity': quantity, 'price': price };
jQuery.post(url, data).always(callback);
};
};
return ProductListingService;
});
这是我的测试
define(['service/ProductListingService'], function (ProductListingService) {
describe('ProductListingService', function () {
var productListingService, server;
beforeEach(function () {
productListingService = new ProductListingService();
server = sinon.fakeServer.create();
});
it('posts and call to /url', function () {
server.respondWith('POST', '/url',
[201, { "Content-Type": "application/json" }, '']
);
var callback = sinon.spy();
productListingService.create('sku', '1', 10.0, callback);
server.respond();
expect(callback.calledOnce).toBeTruthy();
});
it('posts and call to /url', function () {
spyOn(jQuery, "post").andCallFake();
productListingService.create('sku', '1', 10.0, sinon.spy());
expect(jQuery.post.mostRecentCall.args[0]["url"]).toEqual("/api/listing/create");
});
});
});
答案 0 :(得分:0)
我认为更简单的解决方案是用Jasmine的ajax.js(http://jasmine.github.io/2.0/ajax.html)替换sinon:
define(['service/ProductListingService'], function (ProductListingService) {
describe('ProductListingService', function () {
var productListingService;
beforeEach(function () {
productListingService = new ProductListingService();
jasmine.Ajax.install();
});
afterEach(function() {
jasmine.Ajax.uninstall();
});
it('posts and call to /url', function () {
var callback = sinon.spy();
productListingService.create('sku', '1', 10.0, callback);
var request = jasmine.Ajax.requests.mostRecent();
request.response({
"status": 201,
"contentType": "application/json",
"responseText": ""
});
expect(request.method).toEqual("POST");
expect(request.url).toEqual("/url");
expect(callback.calledOnce).toBeTruthy();
});
it('posts and call to /url', function () {
productListingService.create('sku', '1', 10.0, sinon.spy());
expect(jasmine.Ajax.requests.mostRecent().url).toEqual("/api/listing/create");
});
});
});