Getsuga
Getsuga

Reputation: 609

React snapshot test with Jest, how can a child component calls a function from parent component?

I have a basic app for the sack of my training composed of tow Components App and User and a snapshot test file for the User.

The test passes for now but I want to test the methods that update the state of the parent but I don't know how to proceed, Please Help.

App component

import React from 'react'
import './App.css'
import data from './data/users-data.json'
import User from './components/User/User'

export default class App extends React.Component {
  constructor() {
    super()
    this.state = {users: data}
    this.clickFollowHandler = this.clickFollowHandler.bind(this)
    this.clickStarHandler = this.clickStarHandler.bind(this)
  }

  clickFollowHandler(id) {
    this.setState(prevState => {
        const updatedUsers = prevState.users.map(user => {
            if (user.id === id) {
              user.isFollowed === 'active' ? user.isFollowed = 'idle' : user.isFollowed = 'active'
            }
            return user
        })
        return {
            users: updatedUsers
        }
    })
  }

  clickStarHandler(id) {
    this.setState(prevState => {
        const updatedUsers = prevState.users.map(user => {
            if (user.id === id) {
              user.isStared === 'active' ? user.isStared = 'idle' : user.isStared = 'active'
            }
            return user
        })
        return {
            users: updatedUsers
        }
    })
  }

  render() {
    return (
      <div>
        {this.state.users.map(u => {
          return (
            <User 
              key={u.id}
              id={u.id}
              name={u.name}
              date={u.date}
              readingTime={u.readingTime}
              isStared={u.isStared}
              isFollowed={u.isFollowed}
              image={u.image}
              handleFollowClick={this.clickFollowHandler}
              handleStarClick={this.clickStarHandler}
            />
          )
        })}
      </div>
    )
  }
}

User component

import React from 'react'
import classes from './User.module.css'
import myImage from '../../assets/images/avatar.png'
import PropTypes from 'prop-types'


const User = props => {

    return(
      <div className={classes.User} key={props.id}>
        <div className={classes.name}>name: {props.name}</div>
        <button onClick={() => props.handleFollowClick(props.id)}>
          {props.isFollowed === 'active' ? 'Unfollow' : 'Follow'}
        </button>
        <input 
          className={classes.hvrIconPop}
          checked={props.isStared === 'active' ? true : false} 
          onChange={() => props.handleStarClick(props.id)}
          type='checkbox' 
        />
        <div>date: {props.date}</div>
        <div>reading time: {props.readingTime}</div>
        <img src={myImage} alt={props.name} />
      </div>
    )

}

User.propTypes = {
  handleFollowClick: PropTypes.func.isRequired,
  handleStarClick: PropTypes.func.isRequired,
}

export default User

User.test.js

import React from 'react';
import renderer from 'react-test-renderer';

import User from './User';

const users = [{
  "id": "5d552d0058f193f2795fc814",
  "isFollowed": "active",
  "isStared": "idle",
  "image": "./assets/images/avata.png",
  "readingTime": 20,
  "name": "Walton Morton",
  "date": "Aug 9"
}];

it('renders correctly when there are no users', () => {
  const tree = renderer.create(<User 
    users={[]} 
    handleFollowClick={() => 'test'}
    handleStarClick={() => {}} />).toJSON();
  expect(tree).toMatchSnapshot();
});

it('renders correctly when there is one user', () => {

  const tree = renderer.create(<User users={users}
    handleFollowClick={() => 'test'}
    handleStarClick={() => {}}
     />).toJSON();
  expect(tree).toMatchSnapshot();
 });

Upvotes: 0

Views: 1119

Answers (1)

rickdenhaan
rickdenhaan

Reputation: 11298

You pass your User component a mock function (jest.fn()) through its handleFollowClick and handleStarClick props, then simulate whatever is supposed to trigger the parent action (a click event on the <button /> or a change event on the <input />) and test whether the corresponding mock function was called.

I personally always use Enzyme for this sort of thing, but here's how I'd assume it works using react-test-renderer based on this answer:

const mockFollowClick = jest.fn();
const mockStarClick = jest.fn();

const tree = renderer.create(<User
    {...users[0]}
    handleFollowClick={mockFollowClick}
    handleStarClick={mockStarClick}
/>)

const button = tree.root.findByType('button');
const input = tree.root.findByType('input');

button.props.onClick();
expect(mockFollowClick).toHaveBeenCalled();

input.props.onChange();
expect(mockStarClick).toHaveBeenCalled();

You can even check if it was called with the correct user id:

button.props.onClick();
expect(mockFollowClick).toHaveBeenCalledWith("5d552d0058f193f2795fc814");

Upvotes: 1

Related Questions