reactjs - jestで関数のテストケースをどのように書くか?
私は関数を作成しました。その関数のテストケースを書きたいです。その関数ではHTMLコンテンツを返しています。
私の関数コードは-
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>;
}
私はenzymeとjestを使用しており、この関数をテストしてボタンがtrueを返すかを確認したいです。この関数のテストケースはどう書けばいいですか?
回答 #1
Reactテスティングライブラリを使って、次のようなテストを書くことができます:
import { render, fireEvent, wait } from '@testing-library/react'
const { getByTestId } = render(<executeScenario {...props} />)
expect(getByTestId("executescenario")).toBeInTheDocument()
これは、ページ上で指定された id を持つこの要素を見つけることを期待しています。完全なドキュメントや他のことについては、こちらのドキュメントをご覧ください:https://testing-library.com/docs/react-testing-library/intro
回答 #2
Enzyme と Jest を使っている場合、コンポーネントをシャローレンダリングしてから、find メソッドを使って Button がレンダリングされているかを確認することで、上記のことをテストできます。
const wrapper = shallow(<executeScenario buttonTitle='sample' classes='primary' />); // include the required props
const button = wrapper.find(Button);
expect(button).toHaveLength(1);
