【问题标题】:Testing React Component with Jest/Enzyme用 Jest/Enzyme 测试 React 组件
【发布时间】:2017-02-12 17:30:34
【问题描述】:

我正在尝试使用 Enzyme 的浅层包装器来获取我的组件的实例并通过它调用我的类函数。它向我显示了这个错误: TypeError: tree.instance(...).onCampaignSelected 不是函数

class ToolbarPage extends Component {
  constructor(){
    super();
    this.onCampaignSelected = this.onCampaignSelected.bind(this);
    this.state = {
      item: null
    }
  }

  onCampaignSelected (item) {
     this.setState({item})
  }

  render () {
    return (
      <MyComponent onItemSelected={this.onCampaignSelected} />
    )
  }
}
function mapStateToProps(state){
  buttons: state.toolbar.buttons
}
export default connect(mapStateToProps)(ToolbarPage);

我的测试用例是这样的

import { shallow, mount } from 'enzyme';
import ToolbarPage from './ToolbarPage';
import configureStore from 'configureStore';

const store = configureStore();

const props = {
 store,
 isLoggedIn: false,
 messageCounter: 0
}

describe('<ToolbarPage />', () => {
  it('allows to select campaign', () => {
    const tree = shallow(<ToolbarPage {...props}/>);
    tree.instance().onCampaignSelected();
  })
})

我也发现它是一个被包裹的组件,所以我不会在被包裹的组件上得到这个函数。如何访问此功能?

【问题讨论】:

  • 代码好像没问题。 tree.debug() 返回什么?另外,你不会得到propsundefined 的错误吗?您没有错过提供的代码示例中的某些内容吗?

标签: reactjs jestjs enzyme


【解决方案1】:

shallow 不会渲染完整的组件集及其所有属性和方法。它适用于基本的“这件事是否呈现了我的预期?”测试。

mount 会给你一切,并且应该允许你测试你需要的任何东西。它对于测试事件处理和操作组件的状态以测试组件之间的交互非常有用。

【讨论】:

  • 它应该让你调用实例方法。
猜你喜欢
  • 2018-08-20
  • 2017-04-13
  • 2021-06-24
  • 1970-01-01
  • 2020-08-07
  • 2017-11-26
  • 2019-01-29
  • 1970-01-01
  • 2020-01-27
相关资源
最近更新 更多