简体   繁体   中英

Test return value of function with Jest in React

How would I test the return value in the "doSomethingFancy" function in this React code? I tried to find a super simple example and couldn't find anything. So I would like to write a test that checks that the number 2 is returned. I know it doesn't really return to anything as I wrote this as an example so I can learn how to write tests for my React application.

import React from 'react';

class FancyStuff extends React.Component {
    render() {
        return <div>
            <h1>
                Hello, {this.props.name}
            </h1>

            <button onClick={this.doSomethingFancy}>
                Add 1 + 1!
            </button>
        </div>;
    }

    doSomethingFancy(e) {
        e.preventDefault();
        let value = 1 + 1;
        return value;
    }
};

export default FancyStuff;

If you need to access a class method in your test, it will be available as a property on the return of the instance method for your wrapper.

const wrapper = shallow(<MyComponent />);
expect(wrapper.instance().doSomethingFancy()).toEqual(true);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM