jhamm jhamm - 10 months ago 36
React JSX Question

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

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?

Answer Source

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.

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