Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enzyme call method

Let's say I have a method in my React component:

doSomething() {
    // method uses this.props and this.state
}

I want to test this method for different props and states that are set. So how can I call it? MyClass.prototype.doSomething will call the function, but then this.props and this.state are not set.

like image 941
Kousha Avatar asked Aug 23 '16 16:08

Kousha


People also ask

How do you call an Enzyme function?

Enzyme is invoked by calling a function __enzyme_autodiff with the function being differentiated, followed by the corresponding primal and shadow arguments. This will result in the original function being run with the corresponding derivative values being computed.

Does Enzyme shallow call componentDidMount?

As of Enzyme v3, the shallow API does call React lifecycle methods such as componentDidMount and componentDidUpdate .

What is Enzyme shallow rendering?

Shallow rendering lets you render a component “one level deep” and assert facts about what its render method returns, without worrying about the behavior of child components, which are not instantiated or rendered.


1 Answers

You can use enzyme's instance function to get an instance of the rendered component, and call methods on it.

const wrapper = shallow(<MyClass {...props} />) wrapper.instance().doSomething()

like image 54
Tyler Avatar answered Nov 15 '22 23:11

Tyler