0

I am trying to access the props in the button tag so that i can check if it exists. But its giving me a property exists of undefined

function Nav (props) {
    return (
        <nav className='header__nav'>
            <Link to={'/login'}>
                <button className='header__login'>LOGIN</button>
            </Link>
            <Link to={'/register'}>
                <button className='header__register'>SIGN UP</button>
            </Link> 
            <Link to={'/about-me'}>
                <button className='header__aboutme'>ABOUT ME</button>
            </Link>  
            <button className='close__nav' onClick={props.popUpHandler}></button> //want to check if the onClick exists and what happens when i click onto it.
        </nav>
    )
};
    test('on click navigation will be null', () => {
        wrapper = mount(<MemoryRouter><Nav/></MemoryRouter>)

        expect(wrapper.find('button').at(3).exists()).toBeTruthy();  // PASS

        expect(wrapper.find('button').at(3).prop('onClick').exists()).toBeTruthy();  //FAIL
 
    })
  • Does this help? [StackOverflow: Checking if a key exists in a JavaScript object?](https://stackoverflow.com/q/1098040/2430549) – HoldOffHunger Nov 14 '20 at 00:34
  • Not really.. the link you sent me refers mainly to finding keys within an array, I was looking to check how to test it to see if it exist with enzyme/jest –  Nov 14 '20 at 01:57
  • It actually is because `props()` returns an object, and no, the question isn't specific to arrays, it has 'arrays' in the title because of the tag of the same name. – Estus Flask Nov 14 '20 at 21:33

1 Answers1

0

Enzyme exists applies to nodes only , it's not a trivial task to check that a prop exists and there's no dedicated way to do this.

A way to check that a prop exists:

expect(wrapper.find('button').at(3).props()).toHaveProperty('onClick');

A way to check that a prop exists and is defined:

expect(wrapper.find('button').at(3).props('onClick')).not.toBeUndefined();

A correct way to write this test is to assert what exactly the prop should be, i.e. a function:

expect(wrapper.find('button').at(3).props('onClick')).toEqual(expect.any(Function));
Estus Flask
  • 206,104
  • 70
  • 425
  • 565