2

I'm trying to test if the LoginContainer component via props exists in the Header with Enzyme, but I'm not having luck.

Here's my main app:

import React from 'react'
import Header from '../components/Header'
import LoginContainer from './LoginContainer'

const App = () => (
    <Header login={<LoginContainer />} />
)
export default App

My Header:

import React from "react";
const Header = ({login}) =>
    <header role="banner">
        {login}
    </header>
export default Header

And this is my Test:

import React from 'react'
import { shallow } from 'enzyme'
import Header from '../components/Header'

const setup = props => {
    const component = shallow(
        <Header {...props} />
    )
    return {
        component: component
    }
}
describe('Header component', () => {
    it('should render login', () => {
        const { component } = setup();
        console.log(component.props({ login })) //this is undefined
    })
})

The problem is when I run the test it seems that login(LoginContainer) props is undefined. Can someone advice please?

angular_learner
  • 671
  • 2
  • 14
  • 31

2 Answers2

3

You should get the instance first.

NOTE: When called on a shallow wrapper, .props() will return values for props on the root node that the component renders, not the component itself. To return the props for the entire React component, use wrapper.instance().props. See .instance() => ReactComponent

e.g.

            it('should have props', () => {                
                const l = <div>Login ...</div>;
                const {component} = setup({login:l});
                console.log(component.instance().props.login);
                expect(component.instance().props.login).to.exist;
            });
Hosar
  • 5,163
  • 3
  • 26
  • 39
  • The above gives an error: TypeError: Cannot read property 'exist' of undefined. :( – angular_learner Feb 28 '17 at 14:28
  • That's because I'm using Chai for the example. If you are not using Chai, you should use another expectation, like `to.have.length` or `to.equal` depending of what you expect. – Hosar Feb 28 '17 at 14:35
  • I know. I've tried everything `to.have.length`,`to.equal`,`.to.equal(true)`, `toBe(1)` but none of them worked. Always getting `undefined`. I really don't know what I'm doing wrong :( – angular_learner Feb 28 '17 at 14:46
0

You are not passing anything to setup.

import React from 'react'
import { shallow } from 'enzyme'
import Header from '../components/Header'

const setup = props => {
    const component = shallow(
        <Header {...props} />
    )
    return {
        component: component
    }
}
describe('Header component', () => {
    it('should render login', () => {
        const { component } = setup({ login: <LoginContainer/> });
        expect(component.props().login).toBeDefined()
    })
})
Avraam Mavridis
  • 8,698
  • 19
  • 79
  • 133