2

Suppose I have the code below:

<Menu>
  <MenuTrigger text='Select action' />
  <MenuOptions>
    <MenuOption onSelect={() => funcOne()} text='Call funcOne' />
    <MenuOption onSelect={() => funcTwo()} text='Call funcTwo' />
  </MenuOptions>
</Menu>

Now how to unit test (using enzyme) whether the onSelect of first MenuOption calls funcOne and the onSelect of the second MenuOption calls funcTwo?

The testing example in the doc wasn't very helpful as there's no example related to checking the behavior.

usafder
  • 791
  • 5
  • 17

1 Answers1

0

You can test it depending on what exactly are you doing in the funcOne() and funcTwo() functions. Just for an example lets say that you are changing the state of message, then you can test the state value whether its changed or not.

Initialised in the component

this.state = {
  message: ""
}

and you have changed it in funcOne

funcOne() {
 .....
 this.setState({message: "funcOne"});
 ... 
}

As you have 2 MenuOption components, you could give them testIDs.

<Menu>
  <MenuTrigger text='Select action' />
  <MenuOptions>
    <MenuOption testID={"MenuOption1"} onSelect={() => funcOne()} text='Call funcOne' />
    <MenuOption testID={"MenuOption2"} onSelect={() => funcTwo()} text='Call funcTwo' />
  </MenuOptions>
</Menu>

Now you can test like this.

const wrapper = shallow(<Menu/>);
expect(wrapper.state().message).toEqual("");
wrapper.find('MenuOption[testID="MenuOption1"]').simulate("Select");
expect(wrapper.state().message).toEqual("funcOne");

Similarly MenuOption2 can also be tested.

Chandini
  • 540
  • 2
  • 11
  • It's a stateless component. How do I test that funcOne was called after simulating the Select event of the first MenuOption ? – usafder Oct 04 '18 at 11:52
  • What does the funcOne() exactly do? and also please refer to this once. https://medium.com/wehkamp-techblog/unit-testing-your-react-application-with-jest-and-enzyme-81c5545cee45 – Chandini Oct 04 '18 at 12:05
  • Is there a way of giving mock implementation of onSelect of MenuOption ? – usafder Oct 04 '18 at 12:34
  • yeah there is, please refer to above link in the comment – Chandini Oct 04 '18 at 12:37
  • `shallow` is deprecated and has been removed. In addition, one should not access state during tests, and only interact with the UI the way a user would (by pressing buttons etc.). – Elias Feb 08 '22 at 08:00