Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access prop value in react-testing-library

I have been writing a test for my alert.js. I need to access prop value to test its severity. I tried lots of things. But failed every time.

import React from 'react';
import PropTypes from 'prop-types';
import { Snackbar } from '@material-ui/core';
import { Alert as MuiAlert } from '@material-ui/lab';

const Alert = (props) => {
    return (
        <Snackbar
            open={props.open}
            autoHideDuration={3000}
            onClose={props.onClose}
            data-testid='component-alert'
        >
            <MuiAlert
                onClose={props.onClose}
                severity={props.severity}
                data-testid='alert-message'
            >
                {props.message}
            </MuiAlert>
        </Snackbar>
    );
};

Alert.propTypes = {
    message: PropTypes.string.isRequired,
    severity: PropTypes.oneOf(['error', 'warning', 'info', 'success'])
        .isRequired,
    open: PropTypes.bool.isRequired,
    onClose: PropTypes.func.isRequired,
};

export default Alert;

import { render, cleanup } from '@testing-library/react'; import Alert from '../Alert';

const mockFunc = jest.fn(); const defaultProps = { message: 'abc', severity: 'error', open: true, onClose: mockFunc, };

test('render correct severity', () => {
    render(<Alert {...defaultProps}/>)
    //How to access severity prop value here
});

});

like image 811
AMAN KUMAR Avatar asked May 30 '26 19:05

AMAN KUMAR


2 Answers

Following the react-testing-library principles:

The more your tests resemble the way your software is used, the more confidence they can give you.

So there is no point in testing which props your component is receiving. Instead, you should test how the component behaves when these props change.

The appropriate way to test this component would be to assert that the color of the alert is the correct one depending on the severity prop value. You might be able to do so by using getComputedStyles.

like image 167
Toni Bardina Comas Avatar answered Jun 01 '26 09:06

Toni Bardina Comas


You can't access properties

React Testing Library is used to interact with your React components like a human being. What a human being sees is just rendered HTML from your React components

You will have to look up for an HTML element to check the severity

like image 40
ludwiguer Avatar answered Jun 01 '26 08:06

ludwiguer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!