Is there a better way to test React Native class component functions when using Redux and React Router Native?

171 views Asked by At

I'm trying to write tests in Jest for a React Native project I'm working on. I'm using redux and react-router-native and I can't render the components for the tests without wrapping them in a Provider and MemoryRouter. The component I'm trying to test is connected to my Redux store and uses the withRouter function to get access to the router props (history, match, etc.).

I end up with this:

const tree = renderer.create(<Provider store={store}><MemoryRouter><Results /></MemoryRouter></Provider>).toJSON();

This works fine for snapshot tests, but I run into trouble when I try to test the functions in my class component <Results />. I tried using .getInstance() but this returns null because Provider is the parent and it's a functional component.

I was finally able to get to the <Results /> component using .root when rendering but the result is ugly. I have to dig through a few levels of children before I get to it. I'm wondering if there's a better way to test functions on class components that have to be wrapped in Provider and MemoryRouter components to render.

import 'react-native'
import React from 'react'
import { MemoryRouter } from 'react-router-native'
import { Provider } from 'react-redux'
import Results from '../components/results/Results'
import renderer from 'react-test-renderer'
import configureStore from 'redux-mock-store'

import { mockResults } from '../__mocks__/results'

const mockStore = configureStore()

describe('Results page numbers tests', () => {
    let store, tree, results


    beforeEach(() => {
        store = mockStore({
            results: mockResults,
            loader: false,
            resultsLoader: false,
            searchPage: 1,
            query: '',
            pages: []
        })
        tree = renderer.create(
          <Provider store={store}>
            <MemoryRouter>
              <Results />
            </MemoryRouter>
          </Provider>
        ).root;
        
        results = tree.children[0].children[0].children[0].children[0]._fiber.stateNode
    })
    
    it('calculates correct number of pages', () => {
        expect(results.numPages()).toEqual(298728)
    })
})

0

There are 0 answers