我尝试使用jest-dom来测试组件的样式,但遇到了错误:
"TypeError: expect(...).toHaveStyle is not a function"
我的组件是一个带有样式组件的简单链接:
import styled from 'styled-components'
export const Link = styled.a`
color: #fff;
`
在我的测试中,我会:
describe('Link', () => {
it('should display color on the link', () => {
render(<Link href="/x">Test</Link>)
}
expect(screen.getByRole('link', { name: /test/i })).toHaveStyle({ color: '#fff' })
}
我创建了一个设置文件(jest.config.js),其中包含:
module.exports = {
setupFilesAfterEnv: ['<rootDir>/.jest/setup.js'],
}
在项目的根目录下,我创建了. jest/setup.js文件并导入了js-dom:
import '@testing-library/jest-dom'
6条答案
按热度按时间bd1hkmkf1#
你可以试试这个:
对我很有效。
axzmvihb2#
从https://testing-library.com/docs/svelte-testing-library/setup/开始
6.2将以下内容添加到package.json中的Jest配置中
您可以将它添加到您的
jest.config.js
,因为您已经有了它,而不是package.json
。4smxwvx53#
自
@testing-library/dom
v5.0.0以来,compare/v4.2.4...v5.0.0发生了一些重大变化在v5.0.0之前,应使用
import '@testing-library/jest-dom/extend-expect';
从v5.0.0开始,您应该使用
import '@testing-library/jest-dom';
您没有正确添加
expect
的匹配器,这就是您得到错误的原因。oxf4rvwz4#
在您的软件包中使用以下版本:
},
并将此包导入到测试文件中:
第一个月
uurv41yg5#
我从这个link中找到了答案
简而言之:
1.运行:x1月1x
1.将:
import '@testing-library/jest-native/extend-expect'
添加到测试文件1.加:
import { toHaveStyle } from '@testing-library/jest-native/dist/to-have-style'
1.加:
expect.extend({toHaveStyle})
1.最后,
toHaveStyle
满足了您的期望样本代码:
ohtdti5x6#
安装笑话样式组件
然后使用
.toHaveStyleRule
示例: