如何在功能中测试条件?

问题描述 投票:2回答:1

我具有以下条件的此功能。我该如何测试?在其他情况下,它仅测试第一个条件,然后不测试else

handleChange = async (select) => {
  const { data1, data2 } = this.state;
   if (data1.value === 'a') {
    await this.setState({
      data2: {
        ...data2,
        userId: selection.value
      }
    });
  }
   if (data1.value === 'b') {
    await this.setState({
      data2: {
        ...data2,
        list: select
      },
      employees: select
    });
  }
};
javascript reactjs unit-testing jestjs enzyme
1个回答
0
投票

这是单元测试解决方案:

index.jsx

import React, { Component } from 'react';

export default class MyComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data1: { value: 'a' },
      data2: { userId: 1, list: [] },
      employees: [],
    };
  }
  handleChange = async (select) => {
    const { data1, data2 } = this.state;
    if (data1.value === 'a') {
      this.setState({
        data2: {
          ...data2,
          userId: select.value,
        },
      });
    }
    if (data1.value === 'b') {
      this.setState({
        data2: {
          ...data2,
          list: select,
        },
        employees: select,
      });
    }
  };

  render() {
    return <div>my component</div>;
  }
}

index.test.jsx

import MyComponent from '.';
import { shallow } from 'enzyme';
import React from 'react';

describe('61390419', () => {
  it('should handle change if data1.value === "a"', () => {
    const wrapper = shallow(<MyComponent></MyComponent>);
    const select = { value: 2 };
    wrapper.instance().handleChange(select);
    expect(wrapper.state().data2).toEqual({ userId: 2, list: [] });
  });

  it('should handle change if data1.value === "b"', () => {
    const wrapper = shallow(<MyComponent></MyComponent>);
    wrapper.setState({ data1: { value: 'b' } });
    const select = ['1', '2'];
    wrapper.instance().handleChange(select);
    expect(wrapper.state()).toEqual({
      data1: { value: 'b' },
      data2: { userId: 1, list: ['1', '2'] },
      employees: ['1', '2'],
    });
  });
});

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

 PASS  stackoverflow/61390419/index.test.jsx (12.259s)
  61390419
    ✓ should handle change if data1.value === "a" (12ms)
    ✓ should handle change if data1.value === "b" (1ms)

-----------|---------|----------|---------|---------|-------------------
File       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-----------|---------|----------|---------|---------|-------------------
All files  |     100 |      100 |     100 |     100 |                   
 index.jsx |     100 |      100 |     100 |     100 |                   
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        14.371s

源代码:https://github.com/mrdulin/react-apollo-graphql-starter-kit/tree/master/stackoverflow/61390419

© www.soinside.com 2019 - 2024. All rights reserved.