1
votes

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
});

});

1
You're passing defaultProps as the props, so... defaultProps.severity? This is nothing to do with React or props, just accessing a property on an object.jonrsharpe
What I mean is, How can I know whether it rendered severity prop properly or not.AMAN KUMAR
Well what's it supposed to be doing with the value of that prop?! What are you expecting to be displayed as a result? Test for that. Just testing that the value of the prop is the value you're passing as the prop is totally pointless, test the behaviour.jonrsharpe
Basically, I want to test the severity level. But, I can't test it until I have severity prop value.AMAN KUMAR
You do have the severity prop value, because you're passing the severity prop. It's "error".jonrsharpe

1 Answers

0
votes

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