gpt4 book ai didi

javascript - sinon server.autoRespond

转载 作者:行者123 更新时间:2023-11-28 07:35:04 27 4
gpt4 key购买 nike

我正在学习测试,所以我使用 karma、karma-jasmine 和 sinon.js 构建了这个简单的示例:我有一个 ajax 请求,成功后它会设置一个全局变量。使用 sinon fakeServer 我伪造响应,如果我手动使用 sinon.server.respond() 函数触发响应,一切都很好。但是将sinon fakeServer更改为autoRespond = true,却没有达到预期的效果。测试失败,因为全局变量仍未定义。在我看来,当设置为 autoRespond = true 时 fakeRequest 不会应答。有人建议为什么吗?谢谢你的帮助。测试代码:

var requestResult;  // global variable


function loadFirstData () {

var request = $.ajax( {
url : "/rest/first/",
type : "GET",
timeout : 5000,
dataType: "json"
} );

request.done( function ( data ) {
requestResult = data;
} );

request.fail( function ( jqXHR, textStatus ) {
console.error( "Request failed: " + textStatus );
console.error( "Object: ", jqXHR );
} );
}

测试:

describe( 'Ajax requests', function () {
var xhr;

beforeEach(function() {
xhr = sinon.fakeServer.create();

// this doesn't work
//xhr.autoRespond = true;

xhr.respondWith(
'GET',
'/rest/first/',
function (request) {
request.respond(
200,
{ "Content-Type": "application/json" },
'{ "returnValue": 20.13 }'
);
}
);
xhr.respondWith(
'GET',
'rest/second/',
function (request) {
request.respond(
200,
{ "Content-Type": "application/json" },
'{ "returnValue": 3333 }'
);
}
);


});

afterEach(function() {
xhr.restore();
});

it( 'should get first data', function () {
loadFirstData();

// this works
xhr.respond();

expect( requestResult ).toEqual( { "returnValue": 20.13 } );


} );

} );

最佳答案

我自己找到了答案。 :)sinon fake-server 不会立即响应请求,而是会短暂延迟。所以我必须使用 did() Funktion 异步进行 Jasmine 测试。所以下面的代码可以工作:

describe( 'Ajax requests', function () {
var xhr;

// beforeEach get the jasmine done as argument
beforeEach(function(done) {
xhr = sinon.fakeServer.create();

// autoRespond is set
xhr.autoRespond = true;

xhr.respondWith(
'GET',
'/rest/first/',
function (request) {
request.respond(
200,
{ "Content-Type": "application/json" },
'{ "returnValue": 20.13 }'
);
}
);
xhr.respondWith(
'GET',
'rest/second/',
function (request) {
request.respond(
200,
{ "Content-Type": "application/json" },
'{ "returnValue": 3333 }'
);
}
);

// starts the tests
done();

});

afterEach(function() {
xhr.restore();
});

// the asynchronous test get the jasmie done as argument, as well
it( 'should get first data', function (done) {
loadFirstData();

// delays the expectations check
setTimeout( function() {
expect( requestResult ).toEqual( { "returnValue": 20.13 } );

// says jasmine the test is finished
done();
}, 500);

} );

} );

关于javascript - sinon server.autoRespond,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28702108/

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