Anurag Mishra
Anurag Mishra

Reputation: 699

How to write a test cases for a function in jest?

I have created a function and I want to write a test case for that function. I am returning HTML content in that function.

my function code is -

export function executeScenario(handleExecuteScenarioClick: ((event: React.MouseEvent<HTMLButtonElement, MouseEvent>) => void) | undefined, classes: any , buttonTitle:string) {
  return <Button id="executescenario" variant="contained" onClick={handleExecuteScenarioClick} type="button" className={classes.button} color="primary">
    {buttonTitle}
  </Button>;
}

I am using enzyme and jest and I wanna test this function and return a button to be true. How can I write test case for this function ?

Upvotes: 2

Views: 2572

Answers (2)

wentjun
wentjun

Reputation: 42576

If you are working with Enzyme and Jest, you can test for the above by shallow rendering the component, following by checking if Button is rendered by using the find method.

const wrapper = shallow(<executeScenario buttonTitle='sample' classes='primary' />); // include the required props
const button = wrapper.find(Button);
expect(button).toHaveLength(1);

Upvotes: 1

Red Baron
Red Baron

Reputation: 7682

you could use React testing library and write a test like this:

import { render, fireEvent, wait } from '@testing-library/react'

const { getByTestId } = render(<executeScenario {...props} />)

expect(getByTestId("executescenario")).toBeInTheDocument()

this is expecting to find this element with the mentioned id on the page. for the full docs and other stuff you can do, check out the docs here: https://testing-library.com/docs/react-testing-library/intro

Upvotes: 1

Related Questions