用Jest进行快照测试,子组件如何从父组件调用函数?

时间:2019-08-18 19:57:33

标签: reactjs jestjs

我有一个用于解雇培训的基本应用程序,其中包括两个组件应用程序和用户,以及一个用于用户的快照测试文件。

该测试目前通过了,但是我想测试更新父状态的方法,但是我不知道如何进行操作,请帮助。

应用程序组件

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>
    )
  }
}

用户组件

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();
 });

1 个答案:

答案 0 :(得分:1)

您通过其Userjest.fn()道具向handleFollowClick组件传递了一个模拟函数(handleStarClick),然后模拟触发父动作的任何内容({ click上的{1}}事件或<button />上的change事件)并测试是否调用了相应的模拟函数。

我个人总是使用酶来进行这类操作,但是我假设这是基于this answer使用<input />来实现的:

react-test-renderer

您甚至可以检查是否使用正确的用户ID调用了它:

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();