簡體   English   中英

如何開玩笑地模擬另一個反應組件中的函數?

[英]How to jest mock a function living within another react component?

我一直在嘗試為以下反應組件編寫測試,這些組件根據我的道具返回不同的組件:

const Choice: React.FC<States> = props => {
    function getChoiceComponent(): JSX.Element {
        if (props.choices) {
            return <FirstComponent {...props} />;
        } else {
            return <SecondComponent {...props} />;
        }
    }

    return <>{getChoiceComponent()}</>;
};

如何模擬getChoiceComponent函數並對其進行測試?

我們應該通過更改 props 和 state 來測試 react 組件,而不是直接測試getChoiceComponent方法。 這是單元測試解決方案,

index.tsx

import React from 'react';
import FirstComponent from './first';
import SecondComponent from './second';

type States = any;

const Choice: React.FC<States> = (props) => {
  function getChoiceComponent(): JSX.Element {
    if (props.choices) {
      return <FirstComponent {...props} />;
    } else {
      return <SecondComponent {...props} />;
    }
  }

  return <>{getChoiceComponent()}</>;
};

export default Choice;

first.tsx

import React from 'react';
const FirstComponent = () => <div>first component</div>;

export default FirstComponent;

second.tsx

import React from 'react';
const SecondComponent = () => <div>second component</div>;

export default SecondComponent;

index.test.tsx

import Choice from './';
import FirstComponent from './first';
import SecondComponent from './second';
import React from 'react';
import { shallow } from 'enzyme';

describe('60152774', () => {
  it('should render first component', () => {
    const props = { choices: [] };
    const wrapper = shallow(<Choice {...props}></Choice>);
    expect(wrapper.find(FirstComponent)).toBeTruthy();
  });

  it('should render second component', () => {
    const props = {};
    const wrapper = shallow(<Choice {...props}></Choice>);
    expect(wrapper.find(SecondComponent)).toBeTruthy();
  });
});

帶有覆蓋率報告的單元測試結果:

 PASS  stackoverflow/60152774/index.test.tsx
  60152774
    ✓ should render first component (20ms)
    ✓ should render second component (5ms)

------------|---------|----------|---------|---------|-------------------
File        | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
------------|---------|----------|---------|---------|-------------------
All files   |   88.24 |      100 |      50 |     100 |                   
 first.tsx  |      75 |      100 |       0 |     100 |                   
 index.tsx  |     100 |      100 |     100 |     100 |                   
 second.tsx |      75 |      100 |       0 |     100 |                   
------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        3.065s

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM