Tomasz Mularczyk
Tomasz Mularczyk

Reputation: 36169

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

Upvotes: 7

Views: 6681

Answers (1)

Special Character
Special Character

Reputation: 2359

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?

Upvotes: 3

Related Questions