Deborah L. Christinne
Deborah L. Christinne

Reputation: 111

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?

Upvotes: 8

Views: 12358

Answers (1)

BenoitVasseur
BenoitVasseur

Reputation: 782

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.

Upvotes: 8

Related Questions