【问题标题】:Typescript for mounted enzyme wrapper用于安装酶包装的打字稿
【发布时间】:2021-08-15 21:15:48
【问题描述】:

我有一个 expect 语句的测试辅助函数,我发现自己重复了多次。函数如下:

const exampleHelper = (wrapper: AnyObject): void => {
  return expect(
    wrapper
      .find('[data-test="example"]')
      .first()
      .childAt(0)
      .exists()
    ).toBe(true)
}

该函数运行完美,但出于好奇,传递的wrapper 的类型是什么。 wrapper 应该期待一个已安装的包装器,例如:

const wrapper = mount(
  <TestWrapper>
    <ExampleComponent data={mockData} />
  </TestWrapper>
 )

我尝试使用ReactElement,但出现以下错误

Property 'find' does not exist on type 'ReactElement<any, string | JSXElementConstructor<any>>'

【问题讨论】:

  • 我不使用react,但是你不能把鼠标放在mount函数上看看它返回什么类型吗?

标签: reactjs typescript jestjs enzyme


【解决方案1】:

您的wrapper 参数应为ReactWrapper,您的返回应为void

import { mount, ReactWrapper } from "enzyme";

const exampleHelper = (wrapper: ReactWrapper): void => {
  expect(
    wrapper.find('[data-test="example"]').first().childAt(0).exists()
  ).toBeTruthy();
};

我会推荐toBeTruthy 而不是toBe(true),因为.exists() 保证会产生一个布尔值。此外,大多数(如果不是全部)断言方法不返回任何结果,因此没有必要返回期望值。


如果您尝试编写 findByTestId 函数,我建议您在 describe 块的 beforeEach 语句中定义它,那么您不必将 wrapper 作为参数传递:

import { mount, ReactWrapper } from "enzyme";
import Example from "../index";

describe("Example" => {
  let wrapper: ReactWrapper;
  let findByTestId: (id: string) => ReactWrapper;
  beforeEach(() => {
    wrapper = mount(<Example data-test="example-id" />);
    findByTestId = id => wrapper.find(`[data-test='${id}']`);
  })

  it("finds element by test id", () => {
    expect(findByTestId("example-id").exists()).toBeTruthy();
  })
})

或者...如果您正在尝试编写可在任何测试文件中使用的可重用函数,那么您可以执行以下操作:

import type { ReactWrapper } from "enzyme";

/**
 * A testing helper function to find an element by 'data-test'.
 *
 * @function findByTestId
 * @param {ReactWrapper} wrapper
 * @param {string} id
 * @returns {ReactWrapper}
 * @example ```findByTestId(wrapper, "id")```
 */
const findByTestId = (wrapper: ReactWrapper, id: string): ReactWrapper => wrapper.find(`[data-test='${id}']`);

export default findByTestId;

然后在您的测试文件中使用它(findByIdfindByTestId 方式都可以):

import { mount, ReactWrapper } from "enzyme";
import findByTestId from "../../path/to/utils/findByTestId";
import Example from "../index";

describe("Example" => {
  let wrapper: ReactWrapper;
  let findById: (id: string) => ReactWrapper;
  beforeEach(() => {
    wrapper = mount(<Example data-test="example-id" />);
    findById = id => findByTestId(wrapper, id);
  })

  it("finds element by test id", () => {
    expect(findByTestId(wrapper, "example-id").exists()).toBeTruthy();
    expect(findById("example-id").exists()).toBeTruthty();
  })
})

【讨论】:

    猜你喜欢
    • 2022-10-24
    • 2016-10-12
    • 2022-01-25
    • 2015-12-16
    • 2017-02-17
    • 1970-01-01
    • 2020-09-28
    • 2019-12-29
    • 1970-01-01
    相关资源
    最近更新 更多