使用组件中的道具进行单元测试/模拟共享导出功能的正确方法-React

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

在我的React项目中,我有一个共享的导出函数:

//shared_functions.js
export function buildEndpoint(region, methodName) {
   return (region in this.props.regionalEndpointsMap ? this.props.regionalEndpointsMap[region] : this.props.regionalEndpointsMap["default"]) + "/" + methodName;
}

已在多个组件中使用和导入,例如:

//SomeComponent.jsx
import { buildEndpoint } from 'src/util/shared_functions';
....
handleSubmit = async event => {
   let response = await fetch(buildEndpoint(this.state.region, 'methodName'), {
....

问题是由于buildEndpoint函数中的this.props.regionalEndpointsMap,我无法对这个函数进行单元测试。

我的问题是按照最佳实践对此功能进行单元测试的正确方法是什么?独立于使用它的任何组件进行单元测试?从使用它的组件进行测试?尝试独立测试功能时以及尝试从组件测试功能时,无法找到模拟this.props.regionalEndpoints的方法:无法识别该功能:

//test.jsx
....
//props contains regionalEndpointsMap
wrapper = shallow(<SomeComponent {...props} />);
wrapper.instance().buildEndpoint('region', 'method')
//buildEndpoint is unrecognized

作为另一个可能使上述问题产生争议的问题,可以尝试在导出的函数中尝试访问属性(道具),即使不能保证在使用的组件中具有该属性也可以吗?还是皱眉?使用此函数创建基础组件类并使其成为使用它的组件类的父级会更好吗?

很抱歉,这些听起来像是愚蠢的问题,这是React的新功能以及带有笑话和酶的单元测试。

javascript reactjs unit-testing jestjs enzyme
1个回答
0
投票
要独立测试功能,您可以像这样模拟它:

import { buildEndpoint } from 'src/util/shared_functions'; ... let result = ({ props : {regionalEndpointsMap : {default : 'd'} }, buildEndpoint : buildEndpoint }).buildEndpoint("r", "m")

尽管我个人会向该函数传递regionalEndpointsMap,以避免需要访问this上下文。
© www.soinside.com 2019 - 2024. All rights reserved.