MichaelJones MichaelJones - 1 year ago 120
React JSX Question

How to test React PropTypes through Jest?

I'm writing Jest tests for my React code and hoping to make use of/test the PropType checks. I am quite new to the Javascript universe. I'm using npm to install

and have a simple:

var React = require('react/addons');

In my tests. My test looks quite similar to the jest/react tutorial example with code like:

var eventCell = TestUtils.renderIntoDocument(

var time = TestUtils.findRenderedDOMComponentWithClass(eventCell, 'time');
expect(time.getDOMNode().textContent).toEqual('19:00 ');

However it seems that the PropType checks in the
component aren't being triggered. I understand that the checks are only run in Development mode but then I also thought that getting
through npm gave you the development version. The checks trigger in my browser when I build the component with watchify.

What am I missing?

Answer Source

The underlying problem is How to test console.log?

The short answer is that you should replace the console.{method} for the duration of the test. The common approach is to use spies. In this particular case, you might want to use stubs to prevent the output.

Here is an example implementation using Sinon.js (Sinon.js provides standalone spies, stubs and mocks):

import {
} from 'chai';
import DateName from './../../src/app/components/DateName';
import createComponent from './create-component';
import sinon from 'sinon';

describe('DateName', () => {
    it('throws an error if date input does not represent 12:00:00 AM UTC', () => {
        let stub;

        stub = sinon.stub(console, 'error');

        createComponent(DateName, {date: 1470009600000});

        expect(stub.calledWithExactly('Warning: Failed propType: Date unix timestamp must represent 00:00:00 (HH:mm:ss) time.')).to.equal(true);


In this example DataName component will throw an error when initialised with a timestamp value that does not represent a precise date (12:00:00 AM).

I am stubbing the console.error method (This is what Facebook warning module is using internally to generate the error). I ensure that the stub has been called once and with exactly one parameter representing the error.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download