gpt4 book ai didi

jquery - Jasmine 文字验证: How to normalize text?

转载 作者:行者123 更新时间:2023-12-01 02:30:04 24 4
gpt4 key购买 nike

我的页面包含不同 HTML 元素中的文本,我想要一种快速验证文本的方法。

使用 jasmine 和 jasmine-query 加载 HTML 并测试 DOM。

例如,我想验证此 HTML 中的文本

<table id="users">
<thead>
<tr>
<td>user</td>
<td>permissions</td>
<td>last seen</td>
</tr>
</thead>
<tbody>
<tr>
<td>Darren</td>
<td>testuser,customer</td>
<td>today</td>
</tr>
<tr>
<td>Hillary</td>
<td>administrator</td>
<td>yesterday</td>
</tr>
</tbody>
</table>

假设我想验证表中的每一行都包含正确的文本。 Jasmine 测试文件:

    it('should find correct text in table', function () {
expect( $('#users').find('tbody tr').first() ).toContainText('Darren testuser,customer today');
expect( $('#users').find('tbody tr').last() ).toContainText('Hillary administrator yesterday');

});

我会遇到这个失败:

Testexample:: should find correct text in table: failed
Expected '<tr>
<td>Darren</td>
<td>testuser,customer</td>
<td>today</td>
</tr>' to contain text 'Darren testuser,customer today'. (1)
Expected '<tr>
<td>Hillary</td>
<td>administrator</td>
<td>yesterday</td>
</tr>' to contain text 'Hillary administrator yesterday'. (2)
1 spec in 0.283s.
>> 2 failures

另一个实验是使用 jQuery.text() 来提取,然后由于所有空格,我仍然有错误:

    it('should find correct text in table with jQuery.text()', function () {
expect( $('#users').find('tbody tr').first().text() ).toContain('Darren testuser,customer today');
expect( $('#users').find('tbody tr').last().text() ).toContain('Hillary administrator yesterday');

});

失败:

Testexample::  should find correct text in table with jQuery.text(): failed
Expected '
Darren
testuser,customer
today
' to contain 'Darren testuser,customer today'. (1)
Expected '
Hillary
administrator
yesterday
' to contain 'Hillary administrator yesterday'. (2)
1 spec in 0.291s.
>> 2 failures

Capybara(对于 ruby​​)有一种标准化文本的方法,这样我总是可以看到 HTML 的合理文本表示。我如何以一种简单的方式标准化空白,以便我可以进行这样的验证?

(我不希望得到像“你不应该跨 html 元素进行测试”这样的答案...因为这是问题的前提。实际上,我喜欢跨多个元素进行断言:它可读、简短,并且可以快速给出结果查看东西是否正常工作。当我从外到内进行测试时也确实很有必要)

最佳答案

我经常在我的项目中添加这样的东西:

String.prototype.normalizeSpace = function() {
return this.replace(/\s\s+/g, ' ');
}

因此,在 .text() 之后,您只需添加对 .normalizeSpace()

的调用即可

关于jquery - Jasmine 文字验证: How to normalize text?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20686431/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com