Eyal
Eyal

Reputation: 1709

React Enzyme - Testing for a Value of a Specific Prop

My component (<NavItems />):

<Fragment>
    <Nav>
        {items.map((item, i) => (
            <NavItem key={i} url={item} />
        ))}
    </Nav>
</Fragment>

In my test, I want to check whether my component, <NavItems />, contains a <NavItem /> component with a specific url prop, say '/login'.

The problem is that I don't care about the value of the key prop and it shouldn't be part of the test.

How can this be tested?

Thanks in advance.

Upvotes: 1

Views: 2135

Answers (2)

Galupuf
Galupuf

Reputation: 2947

const wrapper = mount(<NavItems />);
expect(wrapper.find(NavItem).filterWhere((item) => {
  return item.prop('url') === '/login'
}).to.have.lengthOf(1);

This will also work with shallow()

Upvotes: 0

uladzimir
uladzimir

Reputation: 5689

You can check the props you want. The method you're looking for is most likely findWhere. Something like the next code should do the trick

const wrapper = shallow(<NavItems />)
const nav = wrapper.shallow()

expect(nav.findWhere(el => el.is(NavItem) && el.prop('url') === '/login').length).toEqual(1)

So main part here is expect, where you can check exactly what you want. Don't forget to pass items array.

With mount you can avoid multiple shallow, but don't forget it's more heavy operation by memory and will render whole the react tree with lifecycle methods.

Upvotes: 2

Related Questions