Jest gives error: "Typeerror: expect(...). toHaveStyle is not a Function"

Asked

Viewed 199 times

0

I’m trying to use jest to test the style of a component, and it’s giving me this error:

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

It is a simple component I created only with Styled-Components:

import styled from 'styled-components'

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

Testing:

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 tried to place some imports: jest-dom, jest-dom/extend-expect, jest-Styled-Components. None of them worked. With jest-dom/extend-expect, the error changes to:

Syntax error parsing expected css: missing '}' on line: 1

    Failing css:
    [object Object]
  • Hi Julio, I don’t know much about React, but the Link should contain the attribute to="" and not href="", despite the documentation stating that it accepts all attributes of <a>, maybe it affects the attribute aria-role, but I can’t say for certain.

  • What version of @testing-library/jest-dom?

1 answer

0

You forgot to close a parenthesis in your test code. The error itself is saying this.

Correction:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.