Mauricio Dziedzinski
Mauricio Dziedzinski

Reputation: 507

How to refer to conditional elements when unit testing React components using jest and enzyme

I'm trying to test a component which should show a login and subscribe button when a user is not authenticated, but should show a logout button when a user is authenticated.

How should I refer to these buttons when making the test?

All examples I found is people doing things like:

expect(wrapper.find(Button).lenght).toBe(1); // or whatever

But this obviously doesn't fit my case, since I always have at least one button and they are all the same, except for its text and action.

So I think I need some way to refer to these buttons, so I could pass an authenticated prop and check if exactly the logout button is rendered.

What would be the best approach on doing that?

Upvotes: 0

Views: 3613

Answers (3)

Ihab
Ihab

Reputation: 1

Just use filter:

wrraper.find(Button).filter({className:'any'})
wrraper.find(Button).filter({label:'any'})

...etc

Upvotes: 0

Code-Apprentice
Code-Apprentice

Reputation: 83527

You need to determine what differentiates each button. First, find the button:

const button = wrapper.find(Button)

Then expect() on some characteristic of the button. For example,

expect(button.props().children).toEqual('Subscribe')

or

expect(button.props().children).toEqual('Logout')

Upvotes: 3

Michael Brewer-Davis
Michael Brewer-Davis

Reputation: 14276

The options for selecting elements can be seen in the documentation for Selector.

In this case, you'd probably want to add css classes and use the class syntax, or perhaps the attribute syntax if your buttons use input elements where the text is set as an attribute.

Upvotes: 3

Related Questions