Jest-dom give the error "TypeError: expect(...).toHaveStyle is not a function"

Viewed 9188

I'm trying to use jest-dom to test a component's styles, and I'm having the error:

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

My component is a simple link with styled-components:

import styled from 'styled-components'

export const Link = styled.a`
  color: #fff;
`

In my test I'm doing:

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

I created a settings file (jest.config.js) with:

module.exports = {
  setupFilesAfterEnv: ['<rootDir>/.jest/setup.js'],
}

At the root of the project I created the .jest / setup.js file and imported the js-dom:

import '@testing-library/jest-dom'
5 Answers

you can try this :

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

it works for me.

Since @testing-library/dom v5.0.0, there are some breaking changes compare/v4.2.4...v5.0.0

Before v5.0.0, you should use import '@testing-library/jest-dom/extend-expect';

Since v5.0.0, you should use import '@testing-library/jest-dom';

You didn't add the matchers for expect correctly. That's the reason you get the error.

Use the following versions in your package:

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

},

and import this package into your test file:

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

I found the answer from this link

To be short:

  1. Run: npm install --save-dev @testing-library/jest-native
  2. Add: import '@testing-library/jest-native/extend-expect' to your test file
  3. Add: import { toHaveStyle } from '@testing-library/jest-native/dist/to-have-style'
  4. Add: expect.extend({toHaveStyle})
  5. Finally, you have the toHaveStyle for your expect

Sample code:

/**
 * @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'
    })
});
Related