【问题标题】:Jest-dom give the error "TypeError: expect(...).toHaveStyle is not a function"Jest-dom 给出错误“TypeError: expect(...).toHaveStyle is not a function”
【发布时间】:2021-03-07 08:19:36
【问题描述】:

我正在尝试使用 jest-dom 来测试组件的样式,但我遇到了错误:

"TypeError: expect(...).toHaveStyle is not a function"

我的组件是一个带有 styled-components 的简单链接:

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'

【问题讨论】:

    标签: reactjs jestjs styled-components react-testing-library jest-dom


    【解决方案1】:

    @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 的匹配器。这就是您收到错误的原因。

    【讨论】:

      【解决方案2】:

      你可以试试这个:

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

      它对我有用。

      【讨论】:

      • 我得到:TypeError: Object.defineProperty 在 Function.defineProperty () 的非对象上调用
      【解决方案3】:

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

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

      },

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

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

      【讨论】:

        【解决方案4】:

        来自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

        【讨论】:

          猜你喜欢
          • 2015-05-04
          • 2018-07-23
          • 1970-01-01
          • 2019-09-25
          • 2022-01-01
          • 2015-11-01
          • 2019-01-28
          • 2021-04-19
          • 1970-01-01
          相关资源
          最近更新 更多