您的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;
然后在您的测试文件中使用它(findById 或 findByTestId 方式都可以):
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();
})
})