gpt4 book ai didi

javascript - 如何 jasmine 测试 jQuery post ajax 属性(例如 url)

转载 作者:行者123 更新时间:2023-12-01 05:51:35 25 4
gpt4 key购买 nike

我有一个基本的 jQuery 帖子到一个 url,我想测试它。我已经做了 Sinon 创建服务器测试,但我也想测试方法中给出的 url 和属性,但我收到错误,因为 jQuery.post(url, data).always(callback) 不能在 undefined object 上调用。

我还应该测试什么?

这是我的 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");
});

});
});

最佳答案

我认为更简单的解决方案是用 Jasmine 的 ajax.js 替换 sinon (http://jasmine.github.io/2.0/ajax.html):

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");
});

});
});

关于javascript - 如何 jasmine 测试 jQuery post ajax 属性(例如 url),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21614359/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com