首页 > 解决方案 > 如何在 Typescript 的功能组件中模拟一个函数?

问题描述

试图弄清楚如何模拟功能组件 Typescript React 中的函数。这是代码...

HeaderBar.tsx

const HeaderBar: React.FC<RouteComponentProps<any>> = (props: any) => {
  const search = e => {
    console.log(e);
  };
};

HeaderBar.test.tsx

import HeaderBar from './HeaderBar';
it('mocks the search function', () => {
   const wrapper = shallow(<HeaderBar />);
   const mock = jest.spyOn(HeaderBar, 'search');
})

我收到以下错误:

无法窥探搜索属性,因为它不是函数;取而代之的是未定义。

我认为这是因为我要测试的功能在另一个功能(即功能组件)内部。我没有使用类,所以我想知道如何模拟这个函数?

标签: reactjsjestjsenzyme

解决方案


您不能模拟 SFC 中定义的函数。而且,我们不应该测试函数的实现细节。我们应该测试 React 组件的行为。这是测试 React Component 的测试背景和策略。

因此,您的示例代码的单元测试是:

HeaderBar.tsx

import React from 'react';

const HeaderBar = (props: any) => {
  const search = e => {
    console.log(e);
  };
  return <div onClick={search}></div>;
};

export default HeaderBar;

HeaderBar.test.tsx

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

it('mocks the search function', () => {
  const logSpy = jest.spyOn(console, 'log');
  const wrapper = shallow(<HeaderBar />);
  const mEvent = { target: 'fake target' };
  wrapper.find('div').simulate('click', mEvent);
  expect(logSpy).toBeCalledWith(mEvent);
});

我们可以监视console.log并测试它是否会被调用。如果setState您的函数中有,您应该使用wrapper.state()测试状态,将其断言为您的预期状态。

100% 覆盖率的单元测试:

 PASS  src/stackoverflow/57154476/HeaderBar.test.tsx
  ✓ mocks the search function (16ms)

  console.log node_modules/jest-mock/build/index.js:860
    { target: 'fake target' }

---------------|----------|----------|----------|----------|-------------------|
File           |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
---------------|----------|----------|----------|----------|-------------------|
All files      |      100 |      100 |      100 |      100 |                   |
 HeaderBar.tsx |      100 |      100 |      100 |      100 |                   |
---------------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        4.506s, estimated 9s

源代码:https ://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/57154476


推荐阅读