Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test required props in React

I'm trying to write simple test with React and Jest.

Component:

import React from "react";

class Task extends React.Component {

    render() {
        let onDelete = this.props.onDelete;
        return (
                <li>
                    <div className="collapsible-header"><i className="material-icons" onClick={() => onDelete(this.props.taskId)}>delete</i>{this.props.title}</div>
                    <div className="collapsible-body"><p>{this.props.description}</p></div>
                </li>
                );
    }
};

Task.propTypes = {
    title: React.PropTypes.string.isRequired,
    taskId: React.PropTypes.number.isRequired,
    onDelete: React.PropTypes.func.isRequired,
    description: React.PropTypes.string
};

Task.defaultProps = {
    description: ''
};

export default Task;

Test

import React from 'react';
import Task from '../src/components/Task';
import renderer from 'react-test-renderer';

test('Task should require properties', () => {
  const component = renderer.create( //this will give me React warnings which I would like to assert
    <Task></Task>
  );
});

Now I would like to assert that title, taskId and onDelete is required for Task component. That I will get React warning about not specifying them (or passing different types).

like image 277
Tomasz Mularczyk Avatar asked Jan 21 '17 13:01

Tomasz Mularczyk


People also ask

How do you pass props in React test cases?

In this post, we will examine how to solve the How To Pass Props In React Test Cases problem using examples from the programming language. it('renders results after search', () => { const fetched = true; const wrapper = mount(<Search store={store} {...fetched}/>); expect(wrapper. find('Results'). length).


1 Answers

You can use a spy to find out if any kind of exception was thrown from react. Many people use a library called Sinon.js. From the documentation "A test spy is a function that records arguments, return value, the value of this and exception thrown (if any) for all its calls".

There is a great solution described in more detail here:

How to test React PropTypes through Jest?

like image 177
Special Character Avatar answered Oct 10 '22 08:10

Special Character