本文介绍了React函数组件中的模拟引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我有React函数组件,其子组件之一具有ref。引用是通过 useRef 创建的。 我想用浅色渲染器测试组件。我必须以某种方式模拟ref来测试其余功能。 我似乎找不到任何方法来引用和模拟它。我尝试过的事情 通过childs属性访问它。 React不喜欢这样,因为ref并不是真正的道具 嘲笑useRef。我尝试了多种方法,只有在我的实现使用 React.useRef 时,它才能与间谍一起使用。 我看不到其他任何方法来引用它来模拟它。在这种情况下是否必须使用mount? 我无法发布真实场景,但我构建了一个小例子 it('should test',()=> { const模拟= jest.fn(); const组件=浅(< Comp onHandle = {mock} />); // @ ts-ignore component.find('button')。invoke('onClick')(); Expect(mock).toHaveBeenCalled(); }); const Comp =({onHandle}:any)=> { const ref = useRef(null); const handleClick =()=> { if(!ref.current)return; onHandle(); }; 返回(< button ref = {ref} onClick = {handleClick}> test< / button>); }; 解决方案这是我的单元测试策略,请使用 jest.spyOn 方法监视 useRef 钩子。 index.tsx : import从'反应'; export const Comp =({{onHandle}:any)=> { const ref = React.useRef(null); const handleClick =()=> { if(!ref.current)return; onHandle(); }; 返回(< button ref = {ref} onClick = {handleClick}> test < / button> ); }; index.spec.tsx : import从'react'进行React; 从酶导入{浅};从’./’导入 {Comp}; describe('Comp',()=> { afterEach(()=> { jest.restoreAllMocks(); }); it('如果ref不存在,则不应该执行任何操作',()=> { const useRefSpy = jest.spyOn(React,'useRef')。mockReturnValueOnce({current:null}); const组件=浅(<>< / Comp>); component.find('button')。simulate('click'); Expect(useRefSpy).toBeCalledWith( null); }); it('应该处理点击',()=> { const useRefSpy = jest.spyOn(React,'useRef')。 mockReturnValueOnce({当前:document.createElement('button')}); const模拟= jest.fn(); const组件=浅(< Comp onHandle = {mock}>< ;; / Comp>); component.find('button')。simulate('click'); Expect(useRefSpy).toBeCalledWith(null); Expect(mock).toBeCalledTimes( 1); }); }); 具有100%覆盖率的单元测试结果: 通过src / stackoverflow / 57805917 / index.spec.tsx Comp ✓如果ref不存在(16ms )✓应该处理点击(3毫秒) ----------- | ---------- | ------ --- | ---------- || ---------- | ------------------- | 文件| %stmts | %分支|功能百分比| %行|未发现的行号| ----------- | ---------- | ---------- | ---------- |- --------- | ------------------- | 所有文件| 100 | 100 | 100 | 100 | | index.tsx | 100 | 100 | 100 | 100 | | ----------- | ---------- | ---------- | ---------- |- --------- | ------------------- | 测试套件:1个通过,总共测试:2个通过,总共2个快照:0个总计时间:4.787s,估计为11s 源代码: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/57805917 I have React function component that has a ref on one of its children. The ref is created via useRef.I want to test the component with the shallow renderer. I have to somehow mock the ref to test the rest of the functionality.I can't seem to find any way to get to this ref and mock it. Things I have triedAccessing it via the childs property. React does not like that, since ref is not really a propsMocking useRef. I tried multiple ways and could only get it to work with a spy when my implementation used React.useRefI can't see any other way to get to the ref to mock it. Do I have to use mount in this case?I can't post the real scenario, but I have constructed a small exampleit('should test', () => { const mock = jest.fn(); const component = shallow(<Comp onHandle={mock}/>); // @ts-ignore component.find('button').invoke('onClick')(); expect(mock).toHaveBeenCalled();});const Comp = ({onHandle}: any) => { const ref = useRef(null); const handleClick = () => { if (!ref.current) return; onHandle(); }; return (<button ref={ref} onClick={handleClick}>test</button>);}; 解决方案 Here is my unit test strategy, use jest.spyOn method spy on the useRef hook.index.tsx:import React from 'react';export const Comp = ({ onHandle }: any) => { const ref = React.useRef(null); const handleClick = () => { if (!ref.current) return; onHandle(); }; return ( <button ref={ref} onClick={handleClick}> test </button> );};index.spec.tsx:import React from 'react';import { shallow } from 'enzyme';import { Comp } from './';describe('Comp', () => { afterEach(() => { jest.restoreAllMocks(); }); it('should do nothing if ref does not exist', () => { const useRefSpy = jest.spyOn(React, 'useRef').mockReturnValueOnce({ current: null }); const component = shallow(<Comp></Comp>); component.find('button').simulate('click'); expect(useRefSpy).toBeCalledWith(null); }); it('should handle click', () => { const useRefSpy = jest.spyOn(React, 'useRef').mockReturnValueOnce({ current: document.createElement('button') }); const mock = jest.fn(); const component = shallow(<Comp onHandle={mock}></Comp>); component.find('button').simulate('click'); expect(useRefSpy).toBeCalledWith(null); expect(mock).toBeCalledTimes(1); });});Unit test result with 100% coverage: PASS src/stackoverflow/57805917/index.spec.tsx Comp ✓ should do nothing if ref does not exist (16ms) ✓ should handle click (3ms)-----------|----------|----------|----------|----------|-------------------|File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |-----------|----------|----------|----------|----------|-------------------|All files | 100 | 100 | 100 | 100 | | index.tsx | 100 | 100 | 100 | 100 | |-----------|----------|----------|----------|----------|-------------------|Test Suites: 1 passed, 1 totalTests: 2 passed, 2 totalSnapshots: 0 totalTime: 4.787s, estimated 11sSource code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/57805917 这篇关于React函数组件中的模拟引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-18 11:54