Jest是一个测试HTML字符串的工具。

6

我该如何使用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())
});

然而,我并不认为仅测试纯字符串值是一种好的方法。
有没有人能帮我找到更好的方式,可以实际测试HTML字符串中的内容?例如测试字符串中的特定类是否具有``标签?就像我们可以使用Enzyme测试React组件一样。
1个回答

14
假设我们正在使用jest和纯JS进行测试。
如果您想测试someFunctionReturningHTMLString是否返回有效的HTML字符串(我认为这很重要),另一个方法是创建一个DOM元素,并使用innerHTML将返回的内容插入节点中,然后您就可以像测试正常HTML一样测试它并确保它有效。
it('should compile partial as per the context', () => {
  const receivedOutput = someFunctionReturningHTMLString();

  // convert output to actual HTML
  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('/')
});

那么测试嵌套元素、文本节点等就会变得非常简单,希望有所帮助。

Jest的文档中有一些关于如何处理DOM操作的示例,它们使用jQuery进行演示,但应用的原则是最重要的。


1
Enmanuel,我差点也做了同样的事情。我知道这是一个旧帖子,但感谢你分享并解释了这些想法。 - Ishwar Patil

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接