javascript 在 React 中使用 Jest 测试函数的返回值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46711679/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 06:52:50  来源:igfitidea点击:

Test return value of function with Jest in React

javascriptreactjstestingjest

提问by Modular Integration

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. Any help would be greatly appreciated.

我将如何测试此 React 代码中“doSomethingFancy”函数的返回值?我试图找到一个超级简单的例子,但找不到任何东西。所以我想编写一个测试来检查是否返回了数字 2。我知道它并没有真正返回任何东西,因为我将它作为示例编写,因此我可以学习如何为我的 React 应用程序编写测试。任何帮助将不胜感激。

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;

回答by EMC

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);