3

我正在尝试使用 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'
4

4 回答 4

2

你可以试试这个:

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

这个对我有用。

于 2020-11-25T08:30:07.800 回答
1

@testing-library/domv5.0.0 开始,有一些重大更改比较/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正确添加匹配器。这就是您收到错误的原因。

于 2020-11-25T03:42:24.780 回答
1

来自https://testing-library.com/docs/svelte-testing-library/setup/

6.2 在 package.json 中将以下内容添加到您的 Jest 配置中

{
  "setupFilesAfterEnv": ["@testing-library/jest-dom/extend-expect"]
}

您可以将它添加到您的jest.config.js,因为您已经拥有它,而不是package.json.

于 2021-07-24T10:02:32.377 回答
0

在您的包中使用以下版本:

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

},

并将此包导入您的测试文件:

import '@testing-library/jest-dom/extend-expect'

于 2021-03-23T02:49:51.553 回答