我将如何测试此 React 代码中“doSomethingFancy”函数的返回值?我试图找到一个 super 简单的例子,但找不到任何东西。所以我想编写一个测试来检查是否返回了数字 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;
最佳答案
如果您需要在测试中访问类方法,它将作为包装器实例方法返回时的属性提供。
const wrapper = shallow(<MyComponent />);
expect(wrapper.instance().doSomethingFancy()).toEqual(true);
关于javascript - 在 React 中使用 Jest 测试函数的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46711679/