user3615045
user3615045

Reputation: 203

Shallow render a functional stateless component -react

I have a functional component in React defined as follows

const MyComponent = ({
   prop1,
   prop2,
   prop3
}, param1 , param2) => {
   return [
//list of spans
      ]
   }

In the spec file, I used shallow to render the component

const fakeObj = {
    prop1:value,
    prop2:value,
    prop3:value
}

shallow(<MyComponent {...fakeObj} param1={something} param2={something} />)

However, when I console.log the params in the MyComponent, I get {} and undefined for param1 and param2 respectively,while the fakeObj is received fine.Is there any way where we can shallow render the component whilst passing object as one of the parameters?

When I just call the component from the spec file as a function ie

MyComponent({fakObj},param1,param2) 

,I get the correct values for params,but not able to find the span elements properly using enzyme.

Upvotes: 1

Views: 951

Answers (1)

webHasan
webHasan

Reputation: 481

React functional component, maybe the function (function to create component) accepts only one parameter to get its props. So you can't define functional component in the way (define multiple parameters) what you did. You have to define it like following.

let MyComponent = (props) => {

    // props is an object, it contains all props passed by component call.
    // So you can get property value as props.propName


    return 'something' // what you like to return. 
}

If you use the component like bellow

<MyComponent prop1="Propone 1 Value" prop2="Prop 2 Value" prop3="Prop 3 Value" /> 

And console props inside your component like

let MyComponent = (props) => {
    console.log(props);
    return 'something' // what you like to return. 
}

You will get all your passed properties as function argument (as props parameter) as an object like below.

{
 prop1:"Propone 1 Value",
 prop2:"Propone 2 Value",
 prop3:"Propone 3 Value"
}

Now come to your requirement. You can create your component like following

let Home = (props) => {

    let {fakeObj, param1, param2} = props;

    return [
        //list of spans
    ]
}

And call component like this

const fakeObj = {
    prop1:value,
    prop2:value,
    prop3:value
}

shallow(<MyComponent fakeObj = {fakeObj} param1={something} param2={something} />)

Upvotes: 1

Related Questions