Reactjs Jest dom给出了一个错误";TypeError:expect(…)。toHaveStyle不是函数;

Reactjs Jest dom给出了一个错误";TypeError:expect(…)。toHaveStyle不是函数;,reactjs,jestjs,styled-components,react-testing-library,jest-dom,Reactjs,Jestjs,Styled Components,React Testing Library,Jest Dom,我试图使用jest dom测试组件的样式,但出现了以下错误: "TypeError: expect(...).toHaveStyle is not a function" My component是带有样式化组件的简单链接: import styled from 'styled-components' export const Link = styled.a` color: #fff; ` 在我的测试中,我正在做: describe('Link', () =>

我试图使用jest dom测试组件的样式,但出现了以下错误:

"TypeError: expect(...).toHaveStyle is not a function"
My component是带有样式化组件的简单链接:

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' })
}

自从
@testinglibrary/dom
v5.0.0以来,出现了一些突破性的变化

在v5.0.0之前,应该使用
import'@testinglibrary/jest-dom/extend-expect'

从v5.0.0开始,您应该使用
import'@testing library/jest-dom'

您没有为
expect
正确添加匹配器。这就是您出现错误的原因。

您可以尝试以下方法:

import { toHaveStyle } from '@testing-library/jest-dom'
expect.extend({ toHaveStyle })

它适合我。

在软件包中使用以下版本:

"dependencies": {
 "@types/styled-components": "5.9.1",
 "styled-components": "^5.2.0"
},

并将此包导入测试文件:

import'@testinglibrary/jest-dom/extend-expect'

import { toHaveStyle } from '@testing-library/jest-dom'
expect.extend({ toHaveStyle })
"dependencies": {
 "@types/styled-components": "5.9.1",
 "styled-components": "^5.2.0"