Javascript Jasmine 测试检查 html 是否包含文本并返回布尔值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29368019/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:16:21  来源:igfitidea点击:

Jasmine tests check if html contains text and return boolean

javascriptjqueryjasminekarma-jasmine

提问by Spdexter

expect(view.$el.html()).toContain('Admin');

The view does contain the word 'Admin' so I was expecting it to return true. How can I achieve this?

该视图确实包含“管理员”一词,因此我希望它返回 true。我怎样才能做到这一点?

expect(view.$el.html()).toContain('Admin');

This returns undefined. How can I make it return true?

这返回undefined. 我怎样才能让它回来true

<header class="main">
  <div id="heading">
    <ul class="header-view right">
      <li class="inline"><a href="#link" class="button help-btn tab-btn"><span>  </span>Help</a></li>
      <li class="inline last"><a href="#og" class="button admin-btn tab-btn expand-admin"><span></span>Admin</a></li>
    </ul>
  </div>
</header>

This is what is returned from view.$el.html

这是返回的内容 view.$el.html

Please help.

请帮忙。

采纳答案by Lee Bailey

From the Jasmine docs:

从茉莉花文档:

The 'toContain' matcher is for finding an item in an Array

'toContain' 匹配器用于在数组中查找项目

You are trying to find a string inside a string so I would do something like this:

您正在尝试在字符串中查找字符串,因此我会执行以下操作:

expect(view.$el.html().indexOf('Admin') !== -1).toBe(true);

回答by alecxe

toContain()now can actually be used for substring in string checks:

toContain()现在实际上可以用于字符串检查中的子字符串

expect(view.$el.html()).toContain('Admin');