Skip to content

Can't access the component's instance #58

@Gpx

Description

@Gpx
  • react-testing-library version: 2.1.1
  • node version: 9.4.0
  • npm (or yarn) version: 5.6.0

Relevant code or config

I'm trying to test this component

import React from 'react' import pick from 'lodash.pick' import { fetchTrips } from '../../../../../api/trips' class TripListState extends React.Component { static defaultProps = { fetchTrips } state = { status: 'LOADING', filter: 'ALL' } async componentDidMount() { const trips = await this.props.fetchTrips('ALL') this.setState({ trips, status: 'READY' }) } handleChangeFilter = async filter => { this.setState({ filter, status: 'FILTERING' }) const trips = await this.props.fetchTrips(filter) this.setState({ trips, status: 'READY' }) } render() { return this.props.children({ ...pick(this.state, ['status', 'trips', 'filter']), onChangeFilter: this.handleChangeFilter, }) } } export default TripListState

It simpliy fetches a list of trips and and exposes a method to change the filter value.

What you did:

This is my attempt to test it:

import React from 'react' import { render, wait } from 'react-testing-library' import TripListState from './TripListState' describe('<TripListState>', () => { it('should fetch the trips on load', async () => { const children = jest.fn(() => null) const trips = [{ id: 1 }] // I pass this as a prop so I can avoid mocking the dependency const fetchTrips = x => Promise.resolve(trips) render( <TripListState children={children} fetchTrips={fetchTrips} /> ) // This works just fine expect(children).toHaveBeenCalledTimes(1) // This errors out expect(children).toHaveBeenCalledWith({ status: 'LOADING', filter: 'ALL', onChangeFilter: /* Not sure what to put here */ }) }) })

What happened:

fail-test

Problem description:

The problem is that I can't access my component's instance and its methods. Not sure what the best approach is here.

Suggested solution:

I'm unsure of this, maybe I'm using react-testing-libraray for something it was not intended to, or maybe my testing approach is wrong. I'm hoping for suggestions :)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions