Jest-styled-components: Components are failing to read values from ThemeProvider context after upgrading to v7+

Created on 30 Sep 2020  路  1Comment  路  Source: styled-components/jest-styled-components

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

Most helpful comment

@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" } }

>All comments

@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" } }

Was this page helpful?
0 / 5 - 0 ratings