简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM