Home > Net >  How to test props in React-typescript?
How to test props in React-typescript?

Time:01-25

I'm working on a react-typescript project and I want to test props passed to a react component using react-testing library.

here is my SharedDashboardUiLatestValueWidget.tsx component

export interface SharedDashboardUiLatestValueWidgetProps {
  title?: string,
  value: number,
  type: 'temperature' | 'humidity',
  varient: 'small' | 'big',
  backgroundColor?:string,
  titleColor?:string,
  valueColor:string
}

export function SharedDashboardUiLatestValueWidget(
  props: SharedDashboardUiLatestValueWidgetProps
) {

  if (props.varient === 'small') {
    return <Card  elevation={4} sx={{ height: '100%', width: '100%', boxSizing: 'border-box',backgroundColor:props.backgroundColor}} >
      <CardContent sx={{ display: 'flex', flexFlow: 'column' }} >
        <Typography  variant='h5' sx={{m:1, fontSize:30,color:props.titleColor}}>
          {props.title || ""}
        </Typography>
        <Typography data-testid="type" variant='h4' sx={{m:1, color:props.valueColor}}>
          { props.value }
          { props.type === 'temperature' ? " °C" : props.type === 'humidity' ? " %" : "" }
        </Typography>
      </CardContent>
    </Card>
...

This is my testing code

describe('SharedDashboardUiLatestValueWidget', () => {

  it('should render SharedDashboardUiLatestValueWidget Props correctly', ()=>{
     render(<SharedDashboardUiLatestValueWidget value={0} type={'temperature'} varient={'big'} valueColor={''} />);
     expect(screen.queryByTestId("type")).toBe('temperature');

  })

});

Even though I passed the values for props I received null value. Can someone help me to test the props in this code ?

CodePudding user response:

Well first things first your variant prop has the value big and your if statement in your component is only true if variant is small so your test not working is to be expected. Also screen.queryByTestId returns a node, if the data-testid is found, which is not comparable to a string, if you want to test for the contents of the element I believe you can use .innerHTML for that. Now that that's out of the way I can tell you how I like to write tests like these. Now keep in mind that I'm not claiming my methods to be the best just what I find to work well. If you want to test if the props work as intended you need to test if the elements in the component are affected as expected depending on the values if your props. For example if you pass props to your component where varient is small, value is 0, and type is temperature you would expect screen.queryByTestId("test").innerHTML to be 0°C. And then make a test where you change one of the props, and check that the component now behaves in a different way as expected.

  • Related