首页 > 解决方案 > 模拟单击我的组件中的另一个组件不起作用

问题描述

下面是我的组件,

interface Props{
onValueChange:(selectedvalue: string, data: string) => void;
}
const MyComp = (props: Props): JSX.Element => {
 return(
  <AnotherComponent
  onValueChange={(value: string, data: string): void => {
            props.onValueChange(value, data);
          }}/>
 );
}

下面是另一个组件

const AnotherComponent = (props:Props):JSX.Element =>{
 return(
  <div
    id={"boxItem" + i.toString()}
   onClick={(): void => {
                      props.onValueChange(value, data);
                    }}
  />
 );
}

下面是我的 MyComp.test 文件,

it("calls onValuechange", () => {
  const changeEvent = jest.fn();
  wrapper.setProps({ onValueChange: changeEvent });
  wrapper
    .find(AnotherComponent)
    .simulate("click",{val:"val",data:"val"});
    expect(changeEvent).toHaveBeenCalledWith("val", "val");
});

运行测试时出现以下错误,

 FAIL  src/components/MyComp/MyComp.test.tsx (5.445 s)
  × calls onValueChange (66 ms)
  MyComp
    √ test component initialization with props (3 ms)

  ● calls onValueChange

    expect(jest.fn()).toHaveBeenCalledWith(...expected)

    Expected: "val", "val"

    Number of calls: 0

      53 |     
      54 |     .simulate("click", { data: "val", value: "val" });
    > 55 |   expect(changeEvent).toHaveBeenCalledWith("val", "val");

      at Object.<anonymous>

不模拟单击 AnotherComponent。我在这里做错了什么吗?提前致谢

标签: reactjsreact-hooksts-jest

解决方案


推荐阅读