octopitus / rn-sliding-up-panel

Draggable sliding up panel implemented in React Native https://octopitus.github.io/rn-sliding-up-panel/
MIT License
928 stars 157 forks source link

Jest/Enzyme Unable to Mock Functions #165

Open RGPosadas opened 4 years ago

RGPosadas commented 4 years ago

Issue Description

Currently doing a unit test using Jest/Enzyme for our project's implementation of the sliding panel. I am testing an onPress event, which also calls SlidingUpPanel.hide(), but can't seem to successfully mock it.

Steps to Reproduce / Code Snippets / Screenshots

Here is my component:

building-information.component code snippet
...
<SlidingUpPanel
        allowDragging={this.state.allowDragging}
        draggableRange={draggableRange}
        animatedValue={this._draggedValue}
        showBackdrop={false}
        ref={c => (this._panel = c)}
        // Speed of the panel
        friction={0.8}
      >
     <View style={styles.container}>
            <TouchableOpacity
              style={styles.xButton}
              onPress={() => {
                onClosePanel();
                this._panel.hide();
              }}
            >
...

However, I get this error when running the test:

TypeError: Cannot read property 'hide' of undefined

      67 |                 onClosePanel();
    > 68 |                 this._panel.hide();
         |                             ^
      69 |               }}

And here is my test file:

sliding-panel.test.js
======================
import React from "react";
import BuildingInformation from "../src/components/building-information/building-information.component";
import renderer from "react-test-renderer";
import { shallow } from "enzyme";

jest.mock("rn-sliding-up-panel", () => {
  return { 
    hide: jest.fn(),
  };
});

it("onClosePanel: check if button is pressed", () => {
    mockOnClosePanel = jest.fn();
    const wrapper = shallow(
      <BuildingInformation tappedBuilding={BuildingId.H} showBuildingInfo={true} onClosePanel={mockOnClosePanel} />
    );
    console.log(wrapper.instance());
    console.log(wrapper.props());
    const button = wrapper.find("TouchableOpacity");
    button.simulate("press"); // Test fails here
  });

Environment