Jest-styled-components: Updating the doc for react native testing

Created on 19 Jul 2019  路  6Comments  路  Source: styled-components/jest-styled-components

Hello there,

a few days ago I was working with your library to set up snapshot tests. When reading your doc, I did not find a lot of information about how to configure your testing library to React Native and Styled Components.

I would like to update your doc to give more information about it. Is it ok for you?

Have a great day,
Thomas.

Most helpful comment

Thanks @tdimnet , I was almost there, just missing a /native in my import :)

All 6 comments

I'm really struggling to get snapshot tests working on react native so I would totally appreciate docs (or just any kind of information at all)

Hey @sampsonjoliver,

I thought I created a PR a few months ago.
Here are the few things I did to make it work:

At the top of your snapshot file:

import 'jest-styled-components'
// do not forget the /native at the end of the line.
import { ThemeProvider } from 'styled-components/native'
import React from 'react'
import renderer from 'react-test-renderer'

If you are using a theme for your application, you need to use the native ThemeProvider.

You then need to import your theme. At SensCritique our theme is a big object literal with some rules within.
I also need to import it:

import theme from 'theme'

Finally the snapshot itself. As you can see I wrap my tested Component into the ThemeProvider component.

describe('Rocket Icon Component Snapshot', () => {
  test('it should render a Default Rocket Icon', () => {
    const tree = renderer
      .create(
        <ThemeProvider theme={theme}>
          <Component />
        </ThemeProvider>
      )
      .toJSON()

    expect(tree).toMatchSnapshot()
  })
})

If it fails again, do not hesitate to print me the errors you have.

Thomas.

Thanks @tdimnet , I was almost there, just missing a /native in my import :)

Yup, using the wrong ThemeProvider in React Native causes errors in the tests but works fine in the application code.

Thank you soo much. was missing /native.

Here is the custom render method I use:
Custom Render Docs: https://testing-library.com/docs/react-testing-library/setup/#custom-render

import 'jest-styled-components/native';
import { ThemeProvider } from 'styled-components/native';
import React from 'react';
import { render } from '@testing-library/react-native';

import * as theme from '../app/theme';

const AllTheProviders = ({ children }) => {
  return <ThemeProvider theme={theme}>{children}</ThemeProvider>;
};

const customRender = (ui, options) =>
  render(ui, { wrapper: AllTheProviders, ...options });

// re-export everything
export * from '@testing-library/react-native';

// override render method
export { customRender as render };
Was this page helpful?
0 / 5 - 0 ratings