Property 'icon' does not exist on type 'HTMLAttributes' - why can't I log out this part of object?

Viewed 771

Running a Jest test in Typescript

test.tsx

it('should render Facebook Icon in Footer', () => {
        const wrapper = mount(<Footer />);
        const renderedProps = wrapper.find('FontAwesomeIcon').at(0).props();
        console.log('rendered props: ', renderedProps); // LOGS OUT
        console.log('rendered props icon: ', renderedProps.icon); // ERRORS
    });

logged out rendered props looks like this:

rendered props:  { 
   onClick: [Function: onClick],
   icon: [Function], // ICON IS VERY CLEARLY THERE.
   size: 'xs'
}

Instead I get this error:

Property 'icon' does not exist on type 'HTMLAttributes'.

I'm very new to Typescript. Wondering if I'm supposed to overwrite the type somehow?

I just want to run checks on the props that are being passed to my mock <FontAwesomeIcon />

Help?

2 Answers

Not sure if this will work but it'll hopefully get you closer

import { AriaAttributes, DOMAttributes } from 'react';

declare module 'react' {
    interface HTMLAttributes<T> extends AriaAttributes, DOMAttributes<T> {
        icon?: Function;
    }
}

I solved a miliar problem by creating an interface for the props to be tested extending HTMLAttributes and adding my own properties; and then asserting the type returned from .props().

In your case, I believe something like this could work (adapt the functions types to your needs):

interface IProps extends HTMLAttributes {
   onClick: (event: MouseEvent) => void;
   icon: () => string; // Or whatever you return as an icon
   size: string;
}

Then use type assertion:

it('should render Facebook Icon in Footer', () => {
  const wrapper = mount(<Footer />);
  const renderedProps = wrapper.find('FontAwesomeIcon').at(0).props() as IProps;
  expect(renderedProps.size).toBe('xs'); // passed OK

I hope it helps!

Related