0

Can anyone help me to write a test case for conditional rendering components using jest and enzyme?

{this.state.addingNewContent ?
          <AddContent
            contentId={this.state.contentId}
            added={this.addContentHandler}
            meta={option}
            closeAddContent={this.closeAddContent}
            assignedData={this.state[option.name]} />
          : <Lock
            lock={this.state.isLocked}
            lockedBy={this.state.lockedBy}
            clicked={() => this.toggleModal(true, 'lock')}>}

1 Answer 1

1

for conditional rendering, you need to mock state like

import AddContent from '../COMPONENT';
import Lock from '../COMPONENT'

it('should render AddContent component', () => {
  const wrapper = shallow(<MyComponent {...props} />);
  wrapper.setState({ addingNewContent: true });
  const component = wrapper.find(AddContent);
  expect(component.length).toBe(1);
});

it('should render Lock Component', () => {
  const wrapper = shallow(<MyComponent {...props} />);
  wrapper.setState({ addingNewContent: true });
  const component = wrapper.find(Lock);
  expect(component.length).toBe(1);
});

It's better to have separate test cases.

Sign up to request clarification or add additional context in comments.

6 Comments

For the else case?
i am getting error like this : expect(received).toBe(expected) Expected: 1 Received: 0
MyComponent is your class component name.
I am still getting this error expect(received).toBe(expected) Expected: 1 Received: 0
could you add your state code of the class component
|

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.