9

I have a conditional rendering block in my React component which is defined as:

 {(props.email.primary.isPending) ?
          <PendingComponent emailAddress={props.email.primary.pendingEmail} />
          :
          <SecondaryEmailContact
            state={props.email.secondary}
            retrieveInputData={props.retrieveInputData}
            handleSecondaryEmailToggle={props.handleSecondaryEmailToggle}
            handleDelete={props.handleDelete}
            handleSubmitContact={props.handleSubmitContact}
            refs={props.refs}
          />
        }

I have written a test case as below:

it('renders the EditEmailContact component', () => {
        wrapper=mount(<EditEmailContact 
          email={emailState}
          handleSecondaryEmailToggle={handleSecondaryEmailToggleFn}
          retrieveInputData={retrieveInputDataFn}
          handleDelete={handleDeleteFn}
          handleSubmitContact={handleSubmitContactFn} />);
    });
  });

So, in my test result it shows the line where the statement for conditional rendering is defined is not tested. So, how do I test the conditional rendering?

1 Answer 1

11

You could create two different test cases passing props to your component. For instance:

const yourProps = {
    email: {
      primary: {
         isPending: true // create test cases passing a different value
      },

    },
  }

  const component = mount(<YourComponent {...yourProps} />)
Sign up to request clarification or add additional context in comments.

8 Comments

@pranami I am glad it helped you out! Happy coding!
@pranami by the way, you could also consider adding a snapshot for this test case, example expect(component).toMatchSnapshot()
I have already added a snapshot.Actually the component I am testing has a lot of child components, around 10-15 guess.So 1 doubt that I have which is: for now I have imported all the child components to my test file and trying to call the component inside the shallow/mount to call it, and that way I am seeing that the coverage is getting increased for each file. But I just want to confirm if this is the correct way.Can you please tell me if I am doing it right?
Also, I have functions inside my components which are like button clicks that changes the state and opens a dialog box, so how do I test those functions?
@pranami please create a new question and link it here thanks!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.