ivp*_*ivp 5 html javascript unit-testing jestjs
如何使用 Jest 测试 HTML 字符串?
现在,我正在使用如下所示的常规字符串比较来执行此操作。当我运行这个测试用例时,它工作正常。
it('should compile partial as per the context', () => {
const receivedOutput = someFunctionReturningHTMLString();
//*PS: someFunctionReturningHTMLString() is function which returns a html string;*
//In above call, lets assume it returns `<a href="/" class="some_class1 some_class2" >`
const expectedResult = `<a href="/" class="some_class1 some_class2" >`;
expect(receivedOutput .trim()).toEqual(expectedResult.trim())
});
Run Code Online (Sandbox Code Playgroud)
但是,我不认为这种测试纯字符串值的方法是一种好方法。
有人可以帮助我用更好的方法来实际测试 HTML 字符串的内容吗?比如测试字符串中的标签是否有特定的类?类似于我们可以使用 Enzyme for React 组件实现的功能。
假设我们正在谈论使用 jest 和 vanilla JS 进行测试。
如果您想测试您是否从someFunctionReturningHTMLString(我认为这很重要)返回有效的 HTML,另一种方法是创建一个 DOM 元素并使用 将返回的内容插入节点中innerHTML,然后您可以将其测试为正常的 HTML 并确保它是有效的:
it('should compile partial as per the context', () => {
const receivedOutput = someFunctionReturningHTMLString();
const newNode = document.createElement('div');
newNode.innerHTML(receivedOutput);
// Assuming your output is `<a href="/" class="some_class1 some_class2" >`
const link = newNode.querySelector('a');
// Test the attributes that matter to you as normal HTML
expect(link.getAttribute('class')).toBe('some_class1 some_class2')
expect(link.getAttribute('href')).toBe('/')
});
Run Code Online (Sandbox Code Playgroud)
然后测试嵌套元素、文本节点等将非常简单,希望它有所帮助。
Jest 的文档有一些关于如何使用 DOM 操作的例子,他们使用 jQuery 来演示,但应用的原则才是最重要的。
| 归档时间: |
|
| 查看次数: |
14915 次 |
| 最近记录: |