SoluableNonagon SoluableNonagon - 1 year ago 98
React JSX Question

React - Testing component propTypes - expecting a failure

I'm trying to test a component and I've been looking at the documentation and I don't have a good reference on how to test their failure.

I would like to test the scenario in which a component is not passed required properties, and hence it would fail to mount.

My current test:

var React = require('react');
var ReactTestUtils = require('react-addons-test-utils');
var Carousel = require('./Carousel.react.js');

Carousel propTypes
propTypes: {
choices: React.PropTypes.array.isRequired, // an array of image URLs
choice: React.PropTypes.string

describe('Carousel', function () {

it('should fail when images array is not provided', function () {
var failed = false;
try {
var CarouselDom = ReactTestUtils.renderIntoDocument(<Carousel/>);
var wrapperDiv = ReactTestUtils.scryRenderedDOMComponentsWithTag(CarouselDom, 'div');
} catch(e) {
failed = true;


Now, while the test succeeds, this doesn't FEEL like the right way to test component failing to mount. What is the correct way?

Answer Source

A slightly elegant way of writing the test using Jest is:

describe('Carousel', () => {
  it('throws when image array is not provided', () => {
    expect(() => {
      var CarouselDom = ReactTestUtils.renderIntoDocument(<Carousel/>);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download