简体   繁体   中英

Sinon.js inline callback on success

I'm using QUnit, Sinon.js (fakeServer) and jQuery (AJAX) to capture and test AJAX calls in my program. I'm having an issue (inconsistency) where the inline-function calls do not get executed.

$.ajax({
    contentType: 'application/x-www-form-urlencoded',
    async: bAsynchronous,
    type: 'POST',
    url: url,
    data: content + getSecurityURL(url,sData), //we need to pass the information for security.
    success: typeof functionA == 'function' && typeof functionB == 'function'
             ? [functionA, functionB] : console.log('Error'),
  });

The expected exectuting behavior is functionA followed by functionB . It works, if I write it ? [functionA(), functionB()] : console.log('Error') ? [functionA(), functionB()] : console.log('Error') this way. Why does it not work without brackets?

Edit 1: Both functions A & B contain a console.log('Working!'); I know the code works correctly if I see 2 Working! logs in the console. I know that the request succeeds because server.requests is not empty and server.requests[0] contains all other AJAX call attributes such as: contentType, type, url & data.

Here's what my QUnit set-up code looks like for sinon (this intercepts all AJAX calls made during testing):

QUnit.module('unit tests', {
    beforeEach: function() {
        server = sinon.fakeServer.create();
    },  
    afterEach: function() {
        delete server;
    }
});

The issue was caused by my set-up. The AJAX call was aborting due to a security configuration (has to do with the url) and therefore did not execute any inline functions. Adding brackets in [functionA(), functionB()] only worked because the functions would execute during the call, but not as the result of the call. Also, both functions would execute if typeof functionA == 'function' && typeof functionB == 'function' returned true regardless of whether or not the call actually went through.

I solved the issue by changing a few security configs. Essentially "whitelisting" certain files to be POSTED to. Thanks to everyone who helped!

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