The Walrus
The Walrus

Reputation: 1208

mocking the return of a function in enzyme

I have this function:

addTheItem = item => {
     return this.itemAlreadyAdded(item) ? this.setState({errorMessageShown: true}) : this.props.addItem(item)
   }

how can I mock this function (which lives in my react component,i.e. not a prop) to return me either true or false so I can test the ternary?

Upvotes: 0

Views: 349

Answers (1)

toufek khoury
toufek khoury

Reputation: 3374

Something like this will let you test the function:

import Component from './Component'
....
const wrapper = Shallow(Component);
expect(wrapper.instance().addTheItem()).toBe(...) // Jest (or whatever you choose)

You can check the state like this:

const wrapper = Shallow(Component);
expect(wrapper.state('errorMessageShown').toBeTruthy() // When this.itemAlreadyAdded(item) returns true.
  • Use enzyme Mount for nested components..

Upvotes: 1

Related Questions