在Jest中创建测试用例以进行渲染

时间:2019-09-23 10:02:41

标签: reactjs jestjs enzyme

我有以下代码要在React中测试

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

在上面的代码中,我需要测试两个条件。但是,在运行以下测试时,正在测试一个分支。

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

在上面的代码中,测试中仅覆盖了else部分。其中的参数是在组件处理期间分配的。我可以通过传递参数来测试吗?

2 个答案:

答案 0 :(得分:1)

您可以使用enzyme的{​​{3}}方法来更改组件状态。以下解决方案仅用于独立测试render方法而没有simulate事件。

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');
    });
  });
});

覆盖率100%的单元测试结果:

 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

答案 1 :(得分:0)

是的,如果我们修改组件内部的状态以适应props中的特定值,并且如果prop没有传递任何内容,则可以提供默认值,例如-:

class CheckState extends Component {
    constructor(props){
        this.state = {
            isDone: props.isDone || false
        };
    }
.......

测试用例也必须是这样的::

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

});
相关问题