开玩笑给错误"TypeError: expect(...).toHaveStyle is not a function"



我正试图使用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'

@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的匹配器。这就是你出错的原因。

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

你可以试试这个:

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

它对我有用。

安装jest样式的组件

npm i -D install jest-styled-components

然后使用.toHaveStyleRule

示例:

import React from 'react';
import { render } from 'react-testing-library';
import Button from '../Button';
import 'jest-styled-components';
describe('<Button />', () => {
it('should render text', () => {
const { getByText } = render(<Button text="Button" />);
expect(getByText('Button')).not.toBeNull();
});
it('should have correct style with background color', () => {
const { getByText } = render(<Button text="Button" color="#fff" />);
expect(getByText('Button')).toHaveStyleRule('background', '#fff');
});
});

在包中使用以下版本:

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

},

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

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

我从这个链接中找到了答案

简而言之:

  1. 运行:npm install --save-dev @testing-library/jest-native
  2. 将:import '@testing-library/jest-native/extend-expect'添加到测试文件中
  3. 添加:import { toHaveStyle } from '@testing-library/jest-native/dist/to-have-style'
  4. 添加:expect.extend({toHaveStyle})
  5. 最后,你有了toHaveStyle

示例代码:

/**
* @format
*/
import 'react-native';
import '@testing-library/jest-native/extend-expect';
import React from 'react';
import App from '../App';
import {render, screen} from '@testing-library/react-native';
import { toHaveStyle } from '@testing-library/jest-native/dist/to-have-style';
expect.extend({toHaveStyle})
it('renders correctly', () => {
render(<App/>);
const text = screen.getByTestId('Sample Text')
expect(text).not.toBeNull();
const button = screen.getByTestId('Sample Button')
expect(button).not.toBeNull();
expect(button).toHaveStyle({
backgroundColor: 'transparent'
})
});

相关内容

  • 没有找到相关文章

最新更新