gpt4 book ai didi

javascript - 如何开 Jest 模拟另一个 react 组件中的函数?

转载 作者:行者123 更新时间:2023-11-28 03:10:42 25 4
gpt4 key购买 nike

我一直在尝试为以下 react 组件编写测试,该组件根据我的 Prop 返回不同的组件:

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;

第二个.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

关于javascript - 如何开 Jest 模拟另一个 react 组件中的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60152774/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com