Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i test a component with setProps() of enzyme

//in my component i have 

{this.props.auth.isLoadding && 
   <p className='text-info positionMessage'>Is registring...</p>
}

//in my test i have 

it('should start a new component with set props', () => {
const props = {
    auth: {
        isAuth: false,
        isLoadding: false
    }
}
    const wrapper = shallow(<ScreensCreateAccount {...props}/>)

    wrapper.setProps({isLoadding: true})
    //here is code for testing if <p>...</p> appeared. how can i do this?
})

my component starts with this.props.auth.isLoadding = false, and when a change it for true, the html too change, adding <p className='text-info positionMessage'>Is registring...</p>. How can i test it using shallow from enzyme?

like image 281
Deborah L. Christinne Avatar asked Jan 29 '19 13:01

Deborah L. Christinne


People also ask

What is setProps?

setProps(nextProps[, callback]) => Self. A method that sets the props of the root component, and re-renders. Useful for when you are wanting to test how the component behaves over time with changing props. Calling this, for instance, will call the componentWillReceiveProps lifecycle method.

How is an enzyme setState?

setState(nextState[, callback]) => Self. A method to invoke setState() on the root component instance, similar to how you might in the methods of the component, and re-renders. This method is useful for testing your component in hard-to-achieve states, however should be used sparingly.

Can props be changed in react?

A component cannot update its own props unless they are arrays or objects (having a component update its own props even if possible is an anti-pattern), but can update its state and the props of its children.


Video Answer


1 Answers

Here is a working example that sticks to your code : https://codesandbox.io/s/r7owz8mykm

In your code you just forgot the auth level in your json for the prop isLoading.

{isLoadding: true}, instead of {auth: {isLoadding: true} }

But be aware that shallow rendering and enzyme may not be the right tool for testing your React component. I used it a bit but now I use react-testing-library : https://github.com/kentcdodds/react-testing-library and I am definitively happy with that. My tests are now more high level and interact with my components like a real user will do. I can refactor my component without breaking my tests, with enzyme it is, well, not so easy to write this kind of tests.

I really encourage you to at least read this and make your own opinion.

https://blog.kentcdodds.com/why-i-never-use-shallow-rendering-c08851a68bb7

If you already have some tests with enzyme no problem, you can use both libraries in the same project.

like image 177
BenoitVasseur Avatar answered Sep 28 '22 11:09

BenoitVasseur