Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test functions other than render in a React class using jest?

Tags:

reactjs

jestjs

I am trying to do some TDD on a React app that I am building. Using jest I am able to test my render function to see if I am getting what I expect to get rendered. What if I want to test some other function in the class? How do I get a hold of it? For example, here is a React class:

var moment = require('moment');
var React = require('react');
var utils = require('./utils');

module.exports = React.createClass({
    days: function() {
        var days = [];
        var nextMonth = this.daysFromNextMonth(days, numberOfDays);
        return days;
    },
    daysFromNextMonth: function(days, numberOfDays) {
        ...
    },
    render: function() {
        var that = this;
        var days = this.days().map(function(day, i) {
            return <li key={day}>{day}</li>
        return (
            <ul className='monthly-view'>
                {days}
            </ul>
        );
    }
});

I want to grab a hold of my days or daysFromNextMonth functions and see if they are returning what I would expect. I tried in jest to get a hold of the function like this:

it('should show an render', function() {
    var result = DailyView.daysFromNextMonth(day, 10)
    ....
});

My error says that I have no method daysFromNextMonth. How do I fix this?

like image 908
jhamm Avatar asked Jan 31 '15 13:01

jhamm


Video Answer


2 Answers

You need to render your component to reference methods on it (akin to instantiating a class before using instance methods):

var view = TestUtils.renderIntoDocument(<DailyView />)
var result = view.daysFromNextMonth(day, 10)

Then you can call any of the instance methods.

like image 129
Nick Tomlin Avatar answered Sep 20 '22 10:09

Nick Tomlin


Using enzyme I found this reference to testing the component's functions, https://github.com/airbnb/enzyme/issues/208.

const component = shallow(<MyComponent />);
component.instance().foo();

You have to get an instance of the component before you can call its methods but this worked for me.

like image 25
Michael Fox Avatar answered Sep 20 '22 10:09

Michael Fox