如何获得Jest对钩子中的代码,对功能组件的覆盖?

时间:2020-04-28 12:55:13

标签: reactjs jestjs react-hooks

在功能组件中,具有以下挂钩/功能:

const [currentTab, setCurrentTab] = useState(index);
const handleTabChange = (event: React.ChangeEvent<{}>, tab: number) => {
    console.log("test handleTabChange: " + tab);
    setCurrentTab(tab);
  };

该挂钩正在由测试(控制台日志)调用,但是其中的代码缺少覆盖范围:“语句未覆盖”。 我进行了一项测试,以验证此选项卡更改的副作用-并且效果很好。 如何获得此“黑匣子”代码的覆盖范围?

非常感谢

1 个答案:

答案 0 :(得分:0)

这是使用附加软件包enzyme的单元测试解决方案。

index.tsx

import React, { useState } from 'react';

export default function MyComponent({ index }) {
  const [currentTab, setCurrentTab] = useState(index);
  const handleTabChange = (event: React.ChangeEvent<{}>, tab: number) => {
    console.log('test handleTabChange: ' + tab);
    setCurrentTab(tab);
  };
  return (
    <div>
      <select onChange={(e) => handleTabChange(e, 1)}>
        <option>chocolate</option>
        <option>strawberry</option>
        <option>vanilla</option>
      </select>
      <span>currentTab: {currentTab}</span>
    </div>
  );
}

index.test.tsx

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

describe('61480694', () => {
  it('should pass', () => {
    const logSpy = jest.spyOn(console, 'log');
    const mProps = { index: 2 };
    const wrapper = shallow(<MyComponent {...mProps}></MyComponent>);
    expect(wrapper.find('span').text()).toBe('currentTab: 2');
    wrapper.find('select').simulate('change');
    expect(wrapper.find('span').text()).toBe('currentTab: 1');
    expect(logSpy).toBeCalledWith('test handleTabChange: 1');
    logSpy.mockRestore();
  });
});

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

 PASS  stackoverflow/61480694/index.test.tsx (11.97s)
  61480694
    ✓ should pass (28ms)

  console.log node_modules/jest-environment-enzyme/node_modules/jest-mock/build/index.js:866
    test handleTabChange: 1

-----------|---------|----------|---------|---------|-------------------
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:        13.844s