单元测试 React 功能组件的功能

时间:2021-05-31 13:37:35

标签: reactjs typescript unit-testing jestjs react-functional-component

无论如何我们可以在 react 函数组件中对函数进行单元测试。由于 wrapper.instance() 将为功能组件返回 null,因此在测试中包含此函数以获得最大覆盖率的最佳方法是什么。


const SimpleFC: React.FC = () => {

    const callbackFunction = () => {
        // Do Stuffs
    }

    return (
        <ChildComponent callback={callbackFunction} />
    )
}

export { SimpleFC };

在这个代码段中,我们如何调用 callbackFunction

提前致谢

1 个答案:

答案 0 :(得分:0)

通过您使用 wrapper.instance() API,我随意认为您使用的是 enzyme 库。您可以使用 .invoke(invokePropName)(...args) => Any 方法直接调用 ChildComponent 上的函数 prop。

例如

SimpleFC.tsx

import React from 'react';
import ChildComponent from './ChildComponent';

const SimpleFC: React.FC = () => {
  const callbackFunction = () => {
    // Do Stuffs
    console.log('Do Stuffs');
  };

  return <ChildComponent callback={callbackFunction} />;
};

export { SimpleFC };

ChildComponent.tsx

import React from 'react';

export default function ChildComponent({ callback }) {
  return <div onClick={callback}>child component</div>;
}

SimpleFC.test.tsx

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

describe('67774847', () => {
  it('should pass', () => {
    const logSpy = jest.spyOn(console, 'log');
    const wrapper = shallow(<SimpleFC />);
    wrapper.invoke('callback')();
    expect(logSpy).toBeCalledWith('Do Stuffs');
    logSpy.mockRestore();
  });
});

测试结果:

 PASS  examples/67774847/SimpleFC.test.tsx (8.752 s)
  67774847
    ✓ should pass (48 ms)

  console.log
    Do Stuffs

      at console.<anonymous> (node_modules/jest-environment-enzyme/node_modules/jest-mock/build/index.js:866:25)

--------------------|---------|----------|---------|---------|-------------------
File                | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
--------------------|---------|----------|---------|---------|-------------------
All files           |      90 |      100 |   66.67 |      90 |                   
 ChildComponent.tsx |   66.67 |      100 |       0 |   66.67 | 4                 
 SimpleFC.tsx       |     100 |      100 |     100 |     100 |                   
--------------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        9.654 s