Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test a React Component Mount with Jest

I'm trying to figure out how to test a react component when initial data gets loaded via ajax on the mount.

var ResourceList = React.createClass({
  componentDidMount: function() {
    api.fetchResources(this.props.type).then(function(raw) {
        console.log(raw);
      this.setState({
        resources: raw
      });
    }.bind(this));
  },

  getInitialState: function() {
    return {
      resources: []
    };
  },

  render: function() {
    var resources = this.state.resources.map(function(resource, index) {
      return (
        <Resource raw={resource} key={index}/>
      );
    });

    return (
      <ul>{resources}</ul>
    );
  }
});

The componentDidMount function calls an API that returns a jquery promise.

var fetchResources = function(type) {
  var endpoint = '/resources';

  return $.ajax({
    url: base + endpoint + '/' + type,
    dataType: 'json',
    headers: headers
  });
}

// Return promise
module.exports = {
  fetchResources: fetchResources
};

My test code looks like this:

describe('something', function() {
  beforeEach(function() {
    React = require('react/addons');
    TestUtils = React.addons.TestUtils;
    ResourceListComponent = require('../app/components/resource-list');

    ResourceList = TestUtils.renderIntoDocument(<ResourceListComponent />);

    // Dummy data from server
    resources = [{
      author: 'author',
      body: 'body'
    }];

    // Add the dummy data from the server
    ResourceList.setState({
      resources: resources
    });
  });


  it('1', function() {
    expect(ResourceList.state.resources.length).toBe(1);
  });
});

The error I am getting is: "TypeError: Cannot call method 'then' of undefined", which is understandable, but how can I correct this?

like image 910
bejm Avatar asked Feb 22 '26 19:02

bejm


1 Answers

If you haven't already (you're not showing if you're doing this when looking at your pasted code) then you need to add either of the two lines below.

jest.dontMock('../app/components/resource-list');

or

jest.dontMock('../path/to/your/apiclient');

Jest mocks all of the required modules dependencies by default which will have your API client always return undefined for any method called.

Secondly, I would like to push for you to use your actual implementation of your API handler and mock out the HTTP call instead using a module like nock. The scopes return by nock will intercept all HTTP calls and let you make expectations on the responses so when mounting your component you could have nock actually return valid data and expect that everything worked.

like image 129
Henrik Andersson Avatar answered Feb 24 '26 08:02

Henrik Andersson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!