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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With