How to test functions other than render in a React

2019-06-17 05:07发布

问题:

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?

回答1:

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.



回答2:

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.



回答3:

Combination of jest and enzyme should do the trick. Check out the jest DOM testing documentation and enzyme.

Basic idea being you can use enzyme to shallow render the components and the manipulate them.