如何使用Jest和React测试库测试className [英] How to test a className with the Jest and React testing library
问题描述
我对JavaScript测试完全陌生,并且正在使用新的代码库.我想编写一个在元素上检查className的测试.我正在使用Jest和 反应测试库 .下面,我有一个测试,该测试将基于variant
道具呈现一个按钮.它还包含一个className,我想对其进行测试.
I am totally new to JavaScript testing and am working in a new codebase. I would like to write a test that is checking for a className on the element. I am working with Jest and React Testing Library. Below I have a test that will render a button based on the variant
prop. It also contains a className and I would like to test that.
it('Renders with a className equal to the variant', () => {
const { container } = render(<Button variant="default" />)
expect(container.firstChild) // Check for className here
})
我试图用hasClass
谷歌搜索像Enzyme一样的属性,但找不到任何东西.如何使用当前库(反应测试库和Jest)解决此问题?
I tried to google for a property like Enzyme has with hasClass
, but I couldn't find anything. How can I solve this with the current libraries (React Testing Library and Jest)?
推荐答案
您可以使用react-testing-library轻松地做到这一点.
You can easily do that with react-testing-library.
首先,您必须了解container
或getByText
等的结果仅仅是DOM节点.您可以像在浏览器中一样与它们进行交互.
First, you have to understand that container
or the result of getByText
etc. are merely DOM nodes. You can interact with them in the same way you would do in a browser.
因此,如果您想知道将什么类应用于container.firstChild
,则可以像container.firstChild.className
这样进行.
So, if you want to know what class is applied to container.firstChild
you can just do it like this container.firstChild.className
.
如果您在 MDN 中了解有关className
的更多信息您将看到它返回 all 应用于您的元素的类,这些类之间用空格隔开,即:
If you read more about className
in MDN you'll see that it returns all the classes applied to your element separated by a space, that is:
<div class="foo"> => className === 'foo'
<div class="foo bar"> => className === 'foo bar'
根据您的情况,这可能不是最佳解决方案.不用担心,您可以使用其他浏览器API,例如 classList
.
This might not be the best solution depending on your case. No worries, you can use another browser API, for example classList
.
expect(container.firstChild.classList.contains('foo')).toBe(true)
就是这样!无需学习仅适用于测试的新API.就像在浏览器中一样.
That's it! No need to learn a new API that works only for tests. It's just as in the browser.
如果您经常检查某个班级,可以通过添加 jest-dom <来简化测试. /a>到您的项目.
If checking for a class is something you do often you can make the tests easier by adding jest-dom to your project.
然后测试变为:
expect(container.firstChild).toHaveClass('foo')
还有很多其他方便的方法,例如toHaveStyle
可以帮助您.
There are a bunch of other handy methods like toHaveStyle
that could help you.
请注意,react-testing-library是一个正确的JavaScript测试实用程序.与其他库相比,它具有许多优点.如果您不熟悉JavaScript测试,建议您加入光谱论坛.
As a side note, react-testing-library is a proper JavaScript testing utility. It has many advantages over other libraries. I encourage you to join the spectrum forum if you're new to JavaScript testing.
这篇关于如何使用Jest和React测试库测试className的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!