I am using sinonjs to test my ajax application.
sinon.stub($, 'ajax').yieldsTo('success',
{
msgtype: 'success',
state: 'loggedin'
});
My problem is: Based on URL in AJAX I want to send arguments differently. How can I achieve that?
If url to $.ajax is: /login
then argument to 'success' should be {state: 'loggedin'}
If url to $.ajax is: /getemail
then argument to 'success' should be {email: '[email protected]'}
------------EDIT--------------
my ajax arguments are {url: '/login', type: "POST", data: request_data, success: function(data){}}
ajaxStub.withArgs({url:'/login'})
is not working.
I am using sinonjs to test my ajax application.
sinon.stub($, 'ajax').yieldsTo('success',
{
msgtype: 'success',
state: 'loggedin'
});
My problem is: Based on URL in AJAX I want to send arguments differently. How can I achieve that?
If url to $.ajax is: /login
then argument to 'success' should be {state: 'loggedin'}
If url to $.ajax is: /getemail
then argument to 'success' should be {email: '[email protected]'}
------------EDIT--------------
my ajax arguments are {url: '/login', type: "POST", data: request_data, success: function(data){}}
ajaxStub.withArgs({url:'/login'})
is not working.
2 Answers
Reset to default 5Sinon stubs have the method stub.withArgs(arg1[, arg2, ...])
which allows you to specify different behaviours with different input parameters to the same function. As the first parameter to $.ajax
is the URL, you can do the following:
const ajaxStub = sinon.stub($, 'ajax');
ajaxStub.withArgs('/login').yieldsTo('success', { state: 'loggedin' });
ajaxStub.withArgs('/getemail').yieldsTo('success', { email: '[email protected]' });
Edit
Because you're passing an object as the only parameter it is probably not easily achievable with withArgs()
or even impossible. I guess the easiest way to work around this issue is to define a custom function that is used in place of $.ajax
. Luckily this is very simple in JavaScript and sinon allows you to provide that replacement function as the third parameter in sinon.stub(object, 'method', replaceFunc)
.
function fakeAjax(obj) {
if (obj.url === '/login') {
return obj.success({ state: 'loggedin' });
}
if (obj.url === '/getemail') {
return obj.success({ email: '[email protected]' });
}
}
sinon.stub($, 'ajax', fakeAjax);
Just make sure you call the correct callbacks when your argument matches your conditions. With this method you can even make it more specific, for instance you can also check that it's actually a POST request.
You can use withArgs
with sinon.match
.
For example:
ajaxStub = sinon.stub(jQuery, 'ajax');
ajaxStub.withArgs(sinon.match({ url: 'https://some_url'})).yieldsToAsync('success', responseData);
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745124495a4612609.html
评论列表(0条)