Ad

Creating Test Cases In Jest For Render

- 1 answer

I have the following code to test in React

render() {
    if (this.state.isDone) {
      return(...)
    } else {
      return(...)
    }
}

In the code above, I need to test both conditions. However, when running the below test, one branch is getting tested.

it('renderTest', () => {
    const wrapper = shallow(<CheckState />);
    expect(wrapper.exists()).toBe(true);
});

In the above code, only the else part gets covered in the test. The parameter in this is assigned during the process of the component. Is it possible for me to test the same by passing a parameter?

Ad

Answer

You can use setState method of enzyme to change your component state. Below solution only for testing the render method independently without simulate an event.

index.tsx:

import React from 'react';

interface ICheckStateState {
  isDone: boolean;
}

export class CheckState extends React.Component<{}, ICheckStateState> {
  constructor(props) {
    super(props);
    this.state = {
      isDone: false
    };
  }

  public render() {
    if (this.state.isDone) {
      return <div>Done</div>;
    } else {
      return <div>Not Done</div>;
    }
  }
}

index.spec.tsx:

import React from 'react';
import { shallow, ShallowWrapper } from 'enzyme';
import { CheckState } from './';

describe('CheckState', () => {
  describe('#render', () => {
    let wrapper: ShallowWrapper;
    beforeEach(() => {
      wrapper = shallow(<CheckState></CheckState>);
    });
    it('should render correctly', () => {
      expect(wrapper.exists()).toBe(true);
      expect(wrapper.text()).toBe('Not Done');
      wrapper.setState({ isDone: true });
      expect(wrapper.text()).toBe('Done');
    });
  });
});

Unit test result with 100% coverage:

 PASS  src/stackoverflow/58059957/index.spec.tsx
  CheckState
    #render
      ✓ should render correctly (8ms)

-----------|----------|----------|----------|----------|-------------------|
File       |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
-----------|----------|----------|----------|----------|-------------------|
All files  |      100 |      100 |      100 |      100 |                   |
 index.tsx |      100 |      100 |      100 |      100 |                   |
-----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        2.819s, estimated 6s
Ad
source: stackoverflow.com
Ad