【问题标题】:How to pass prop to child component如何将道具传递给子组件
【发布时间】:2025-12-04 18:20:03
【问题描述】:

我正在尝试在我的组件中测试一个按钮组件,但我不知道如何将 mockFn 传递给 childComponent

我可以通过浅层获取 ParentComponent,然后找到子组件,但我如何传递模拟函数?

<ParentComponent>
    <ChildComponent onPress={this.myFunction}/>   
</ParentComponent>

const mockFunction = jest.fn();

describe("<ParentComponent> behaviour", () => {
 it("should call onSubmit", () => {
   const wrapper = shallow(<ParentComponent />);

   //How pass the mockFn here
   wrapper.find(ChildComponent).simulate('click');

   expect(mockFunction).toHaveBeenCalled();

我该怎么做?

【问题讨论】:

    标签: react-native jestjs enzyme


    【解决方案1】:

    我想你应该直接在子组件中测试这个,像这样:

    const mockFunction = jest.fn();
    
    describe("<ParentComponent> behaviour", () => {
        it("should call onSubmit", () => {
            const wrapper = shallow(<ChildComponent onPress={mockFunction} />);
            wrapper.simulate('click');
            expect(mockFunction).toHaveBeenCalled();
        }
    

    【讨论】:

      【解决方案2】:
      <ParentComponent
      text = {'hey There'}>
          <ChildComponent 
      alert(this.props.text)
      onPress={this.myFunction}/>   
      </ParentComponent>
      

      【讨论】:

        最近更新 更多