jayko03
jayko03

Reputation: 2481

How to pass correct props for enzyme unit test?

I have a component which mainly returns html.

//MainRender.js
function changeOnClick(arg){
  return (
    console.log(arg)
  )
};
    
function helper1(arg) {
  return (
    <div className="helper1" onClick={(e) => changeOnClick(e.target.value)}>
      <span> Helper1: {arg.isHelper1} </span>
    </div>
  );
}

function helper2(arg) {
  return (
    <div className="helper2" >
      <span> Helper2: {arg.isHelper2} </span>
    </div>
)};

export default function MainRender(props){
  const theValue = props.value;
  if(theValue.isHelper1){
    return helper1(theValue)
  } else {
    return helper2(theValue)
  }
 };

and my test is,

import { mount } from 'enzyme';
import React from 'react';

import MainRender from './MainRender';

describe("Testing MainRender", () => {
  it("it should return true when isHelper1 is true", ()=> {
    const tempValue = {"value": {"isHelper1":true, "isHelper2": false}};
    const wrapper = mount(<MainRender props={tempValue} />); // error occurs here
 }
});
Error: Uncaught [TypeError: Cannot read property 'isHelper1' of undefined]

When I debug this test, its structure actually look like this,

props
  |-props
      |-value
         |-isHelper1
         |-isHelper2

I think the problem is, props is nested and it is not assigned to theValue properly. How can I pass argument properly in enzyme unit test? The function itself works just fine.

Upvotes: 0

Views: 25

Answers (1)

Lin Du
Lin Du

Reputation: 102207

You added an extra props property to the component which don't need to. The attributes of JSX will be composed to the props object. It should be:

const tempValue = { value: { isHelper1: true, isHelper2: false } };
const wrapper = mount(<MainRender {...tempValue} />);

Upvotes: 1

Related Questions