Chase Lundell Chase Lundell - 1 year ago 68
jQuery Question

Testing Jquery selector with Jasmine unit tests

$('.froala > div > div > div > p').each(function (index, element) {
if ($(element).text() !== '') {
wordCount += $(element).text().split(' ').length;

I have this code that gets all the < p > tags in the froala editor and counts them. I need to write a Jasmine unit test to cover this and I don't have a clue how to do that. Maybe I could use a spyOn and return an array of < p > tags...

spyOn($('.froala > div > div > div > p'), 'each').and.returnValue([all, my, tags, here]);

Any other ideas?

Answer Source

You shouldn't really be writing tests to test jQuery, and jasmine is not meant to test the dom. You should only write tests for your own code, and have deterministic input/output.

    var myFunction = function(index, element) {
                                if ($(element).text() !== '') {
                                    wordCount += $(element).text().split(' ').length;
     var jquerySelector = ".froala > div > div > div > p";

     $(jquerySelector).each(myFunction });

Then write jasmine tests that import above file and have the expected froala html

var wordCount = 0;
var testhtml = '<div class="froala"><div><div><div><p>one</p><p>two</p></div></div></div></div>';

 expect( wordCount ).toEqual(2)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download