How to test functions other than rendering in the React class using jokes?

I am trying to make TDD in a React application that I am creating. Using jest , I can check my rendering function to see if I get what I expect to receive. What if I want to check out some other functions in the class? How can I hold this? For example, here is the 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 my days or daysFromNextMonth and see if they return, which I would expect. I tried in jest to get a function like this:

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

My error says that I do not have the daysFromNextMonth method. How to fix it?

+7
reactjs jestjs
source share
3 answers

You need your component to refer to methods on it (akin to creating an instance of a class before using instance methods):

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

You can then call any of the instance methods.

+10
source share

Using the enzyme, I found this link to test component functions, https://github.com/airbnb/enzyme/issues/208 .

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

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

+2
source share

The combination of jest and enzyme should do the trick. Check out jest DOM testing and enzyme .

The basic idea: you can use enzyme to fine-tune components and manipulate them.

0
source share

All Articles