【问题标题】:How to write a test cases for a function in jest?如何开玩笑地为函数编写测试用例?
【发布时间】:2020-06-12 06:05:58
【问题描述】:

我创建了一个函数,我想为该函数编写一个测试用例。我在该函数中返回 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>;
}

我正在使用酵素和玩笑,我想测试这个功能并返回一个按钮为真。 如何为这个函数编写测试用例?

【问题讨论】:

  • 你想测试什么?那就是返回一个 React 元素?还有什么?请将您的问题缩小到更具体的问题并包括预期结果。
  • 你到底想测试什么?你在用酵素和玩笑吗?
  • 是的,我正在使用酵素和玩笑,我想测试这个功能并返回一个按钮为真。
  • @wentjun 我已经更新了我的问题。请检查
  • @Drew Reese 请立即查看我的问题

标签: reactjs typescript jestjs enzyme


【解决方案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

【讨论】:

  • 我们不能渲染函数。它正在抛出错误
  • OP 没有渲染功能组件,需要使用data-testid=".." 才能使getByTestId 工作。
【解决方案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);

【讨论】:

  • 没有重载匹配executeScenario上的这个调用。收到此错误。
  • 现在它说没有参数被传递
  • 哦,我刚刚意识到executeScenario 是一个组件.. 已编辑。
  • 这是一个函数。所以现在你能再告诉我一次吗
猜你喜欢
  • 2019-07-23
  • 2019-01-04
  • 2020-07-20
  • 2022-07-04
  • 2017-10-20
  • 2018-09-25
  • 1970-01-01
  • 1970-01-01
  • 2020-08-24
相关资源
最近更新 更多