Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

129
Views
Prueba unitaria renderTags prop de Autocompletar

Me he quedado atascado tratando de probar unitariamente la propiedad renderTags de un componente de Autocomplete mui. Creé un componente personalizado que usa esto. Pero no puedo averiguar cómo probarlo unitariamente. A continuación les mostraré lo que he probado hasta ahora.

El componente se ve así:

 function ChipInput(props: Props): ReactElement { const [field, meta, { setValue }] = useField<string[]>(props.name); const errorText = (meta.touched && meta.error) || undefined; const handleChange = useCallback((_, value) => setValue(value), [setValue]); const renderTags = (value: string[], getTagProps) => value.map((option: string, index: number) => ( <Chip variant="outlined" label={option} {...getTagProps({ index })} /> )); const renderInput = params => ( <TextField {...params} variant="filled" label={props.label} error={errorText !== undefined} helperText={errorText || props.helperText} /> ); return ( <Column column={props.column}> <Autocomplete id={`chipInput-${props.name}`} multiple options={[]} value={field.value || []} onChange={handleChange} freeSolo renderTags={renderTags} renderInput={renderInput} /> </Column> ); }

Y así es como actualmente estoy tratando de probarlo unitariamente. Funciona así para renderInput pero no para renderTags :

 describe('ChipInput', () => { const useFieldMock = jest.spyOn(Formik, 'useField'); const flavours = mockUseField<unknown>(['salt', 'paprika']); const props: ComponentProps<typeof ChipInput> = { name: 'chipInput', label: 'Chip input', column: 1, }; it('should render chips', () => { jest.clearAllMocks(); useFieldMock.mockReturnValue(flavours); const component = shallow(<ChipInput {...props} />); const autocomplete = component.find(Autocomplete); console.log(autocomplete.prop('value')); const renderTags = autocomplete.prop('renderTags') as () => ReactElement; const input = shallow(renderTags()); expect(input).toExist(); }); });

En el registro de la consola, puedo ver [ 'salt', 'paprika' ] impreso, por lo que sé que el valor se configuró correctamente. Pero de alguna manera, en shallow(renderTags()) arroja el error TypeError: Cannot read property 'map' of undefined , porque aparentemente en renderTags el parámetro de valor todavía está vacío. Aunque como se ve en el registro de la consola, se ha configurado.

¿Alguien puede señalarme en la dirección correcta? Siento que debo malinterpretar algo. ¡Gracias por adelantado!

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

El problema es que cuando toma autocomplete.prop('renderTags') devuelve la función renderTags que definió en el componente tal cual. Y su tipo no es () => ReactElement sino (value: string[], getTagProps: Function) => ReactElement[] . Luego llama a renderTags sin argumentos, el value no está undefined y obtiene el error cuando se value.map(...) . Para solucionar el problema, debe pasar un conjunto adecuado de argumentos:

 // I've made the second argument(getTagProps) return an empty object // update with what you expect const input = shallow(renderTags(['salt', 'paprika'], () => ({})));

En general, sugeriría renderTags del componente y hacerlo exportable, para que pueda probarse de forma aislada. Esto facilitaría mucho las pruebas (no es necesario renderizar todo el componente).

about 4 years ago · Juan Pablo Isaza Report

0

Intente llamarlo pasando argumentos como este ..

 const component = shallow(<ChipInput {...props} />); const autocomplete = component.find(Autocomplete); autocomplete.at(0).prop('renderTags')(['salt', 'paprika'],{})
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!