Last Updated: July 29, 2016
·
5.776K
· mateuszgachowski

jQuery chain testing with sinonJS

If you want to test something like this:

$('.selector').siblings('.siblings').toggleClass('hidden');

You can easily try this:

// Fake jQuery methods
var jQueryMethods = { toggleClass: empty, siblings: empty };

// First the methods that can be chained
sinon.stub(jQueryMethods, 'toggleClass').returns(jQueryMethods);
sinon.stub(jQueryMethods, 'siblings').returns(jQueryMethods);

// Then all jQuery function
sinon.stub(window, '$').returns(jQueryMethods);

And now you have full test-ready faked jQuery methods!

thanks for MS

6 Responses
Add your response

Well done mate, glad you posted it here!

over 1 year ago ·

Thanks to YOU!

over 1 year ago ·

Very helpful!
But one thing: You shouldn't use "toggleClass", will you? Apart from it - .removeClass

over 1 year ago ·

I'm glad that it was helpful.
Just fixed! Thank you!

over 1 year ago ·

Thanks for this! Saved me a big headache when I switched my Express response calls from the deprecated res.json(status, body) calls to the new res.status(status).json(body) format. Cheers!

over 1 year ago ·

Happy to help :)

over 1 year ago ·