简体   繁体   中英

how to call sinon stub yieldsTo a function depending on arguments

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: 'test@test.com'}

------------EDIT--------------

my ajax arguments are {url: '/login', type: "POST", data: request_data, success: function(data){}}

ajaxStub.withArgs({url:'/login'}) is not working.

Sinon 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: 'test@test.com' });

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: 'test@test.com' });
  }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM