styled-components / jest-styled-components

🔧 💅 Jest utilities for Styled Components
MIT License
1.59k stars 145 forks source link

Components are failing to read values from ThemeProvider context after upgrading to v7+ #342

Open enginaryum opened 4 years ago

enginaryum commented 4 years ago

Hi guys, recently I've been trying to upgrade styled-components to 5.2.0 and jest-styled-components to 7.0.3.

During my trials, I've found that when I pass theme values using ThemeProvider context, I get No style rules found on passed Component error and tests are failing. But, when I pass them as an inline prop tests are passing.

Is there something I'm missing here?

package.json

"jest-styled-components": "^7.0.3",
"styled-components": "^5.2.0",
"react-test-renderer": "^16.13.1",
"react": "^16.9.0",
"react-dom": "^16.9.0",

test snippet

import React from 'react'
import renderer from 'react-test-renderer'
import styled, { ThemeProvider } from 'styled-components'
import 'jest-styled-components'

const Button = styled.button`
  color: ${(p) => p.theme.color};
`

describe('Button', () => {
  // ------ this is passing 👍 
  it('use color from inline props', () => {
    const app = renderer.create(<Button theme={{ color: 'blue' }} />).toJSON()
    expect(app).toHaveStyleRule('color', 'blue')
  })

  // ------ this is failing 👎 
  it('use color from ThemeProvider context', () => {
    const app = renderer
      .create(
        <ThemeProvider theme={{ color: 'blue' }}>
          <Button />,
        </ThemeProvider>,
      )
      .toJSON()
    expect(app).toHaveStyleRule('color', 'blue')
  })
})

test results

image

ghost commented 3 years ago

@enginaryum I had the same issue. Solved by adding this in jest.config.js "moduleNameMapper": { "styled-components": "<rootDir>/node_modules/styled-components/native/dist/styled-components.native.cjs.js" } }