我正在尝试使用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'发布于 2020-11-25 16:30:08
您可以尝试这样做:
import { toHaveStyle } from '@testing-library/jest-dom'
expect.extend({ toHaveStyle })这对我很管用。
发布于 2020-11-25 11:42:25
从@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的匹配器。这就是你得到错误的原因。
发布于 2021-03-23 10:49:52
在您的软件包中使用以下版本:
"dependencies": {
"@types/styled-components": "5.9.1",
"styled-components": "^5.2.0"},
并将此包导入到测试文件中:
import '@testing-library/jest-dom/extend-expect'
https://stackoverflow.com/questions/64988386
复制相似问题