Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
like image 401
Modular Integration Avatar asked Oct 12 '17 14:10

Modular Integration


People also ask

How do you write test cases for functions in Jest?

To create a test case in Jest we use the test() function. It takes a test name string and handler function as the first two arguments. The test() function can also be called under the alias - it() .

How do you expect a function in Jest?

The expect function is used every time you want to test a value. You will rarely call expect by itself. Instead, you will use expect along with a "matcher" function to assert something about a value. expect(bestLaCroixFlavor()).

How do you use spyOn function in Jest?

To spy on an exported function in jest, you need to import all named exports and provide that object to the jest. spyOn function. That would look like this: import * as moduleApi from '@module/api'; // Somewhere in your test case or test suite jest.


1 Answers

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);
like image 150
EMC Avatar answered Oct 25 '22 14:10

EMC