如何在Jest Mock中调用React.Component的实例方法
集成测试中Mock React类组件的问题
需求说明
我在做集成测试时需要Mock以下React类组件:
interface MyComponentProps { acceptableRoles: string[]} export default class MyComponent extends Component<React.PropsWithChildren<MyComponentProps>> { public canRender(currentRoles: string[]): boolean { // 判断当前角色是否与允许角色有交集 } public render() { return ( <MyContext.Consumer> {(roles) => this.canRender(roles) ? this.props.children : null } </MyContext.Consumer> } }
需求是:Mock该组件的render()输出,移除<MyContext.Consumer>的包装,同时在Mock中传入自定义的roles参数。
该组件在被测组件中的使用方式如下:
<MyComponent acceptableRoles={["role1", "role2"]}> <div>Show this if allowed</div> </MyComponent>
问题重现
我尝试了多种方案,目前的实现最接近需求,但调用origin.canRender时触发错误提示origin.canRender is not a function,检查后发现该方法为undefined:
const myTestRoles = ["role3", "role4"]; // 不同测试用例会修改这个值 jest.mock("./MyComponent", () => (props: any) => { const origin = jest.requireActual<MyComponent>("./MyComponent"); // console.info("Origin: " + origin.canRender); // 输出为 "Origin: undefined" return <div>{ origin.canRender(myTestRoles) ? props.children : null} </div>; });
除了调用origin.canRender的部分,其余代码都能正常运行。
疑问
我知道在严格单元测试中可以直接MockcanRender方法,但想确认:是否能够在这种Mock组件的场景中调用类的实例方法?
内容的提问来源于stack exchange,提问作者JamesEggers
相关产品推荐
相关产品推荐

