为什么jest.spyOn找不到我的组件函数?

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

假设我有这个简单的React(TypeScript)组件:

function Header(): JSX.Element {
   function onChangeFunc(event: Event, tab: number): void {
       // do something...
   }

   return (
      <div>
         <Tabs value={currentTab} onChange={onChangeFunc}>
            <Tab label="A" />
            <Tab label="B" />
         </Tabs>
      </div>
   );
}

我想测试(Jest,TypeScript)Tabs.onChange正在调用onChangeFunc。我应该如何测试?类似于:

const wrapper = shallow(<Header />);
const spyFunc = jest.spyOn(Header, 'onChangeFunc');
wrapper.find('Tabs').simulate('change');
expect(spyFunc).toBeCalled();

关于spyOn中的第二个参数,我遇到了错误:

TS2345: Argument of type '"onChangeFunc"' is not assignable to parameter of type 'never'.

我在做什么错?

reactjs typescript jestjs react-component spyon
1个回答
0
投票

正如@jonrsharpe所说,在onChangeFunc SFC中定义的Header是私有的。我们无法访问它,因此我们无法对其进行监视。您应该通过触发change事件对其进行测试。

例如

index.tsx

import React from 'react';

export const Tabs = ({ onChange, children }) => <select onChange={onChange}>{children}</select>;
const Tab = ({ label }) => <option value={label}>{label}</option>;

export function Header(): JSX.Element {
  function onChangeFunc(event: Event, tab: number): void {
    console.log('onchange');
  }

  return (
    <div>
      <Tabs onChange={onChangeFunc}>
        <Tab label="A" />
        <Tab label="B" />
      </Tabs>
    </div>
  );
}

index.test.tsx

import { Header } from './';
import React from 'react';
import { mount } from 'enzyme';

describe('60927553', () => {
  it('should pass', () => {
    const logSpy = jest.spyOn(console, 'log');
    const wrapper = mount(<Header></Header>);
    const mEvent = {};
    wrapper.find('select').simulate('change', mEvent);
    expect(logSpy).toBeCalledWith('onchange');
  });
});

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

 PASS  stackoverflow/60927553/index.test.tsx (7.617s)
  60927553
    ✓ should pass (57ms)

  console.log node_modules/jest-environment-enzyme/node_modules/jest-mock/build/index.js:866
    onchange

-----------|---------|----------|---------|---------|-------------------
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:        8.86s, estimated 9s
© www.soinside.com 2019 - 2024. All rights reserved.