Testing Jquery selector with Jasmine unit tests

好久不见. 提交于 2019-12-11 05:11:20

问题


$('.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?


回答1:


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

 $(testhtml).find(jquerySelector).each(myFunction)
 expect( wordCount ).toEqual(2)


来源:https://stackoverflow.com/questions/38468165/testing-jquery-selector-with-jasmine-unit-tests

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!