使用Jasmine单元测试测试Jquery选择器 [英] Testing Jquery selector with Jasmine unit tests

查看:381
本文介绍了使用Jasmine单元测试测试Jquery选择器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我有这个代码可以获得所有<在froala编辑器中标记并计算它们。我需要编写一个Jasmine单元测试来覆盖这个,我不知道如何做到这一点。也许我可以使用spyOn并返回一个< p>标签...

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

还有其他想法吗?

推荐答案

你不应该真正编写测试来测试jQuery,而jasmine并不是要测试dom。您应该只为自己的代码编写测试,并具有确定性的输入/输出。

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

然后编写导入上面文件并具有预期froala html的jasmine测试

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)

这篇关于使用Jasmine单元测试测试Jquery选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆