Jest react expect.string contains 与 tohavevalue 结合失败

问题描述

我尝试在带有 create-react-app 的 jest 测试脚本中使用 expect.string contains 对字符串进行对等匹配,但它不起作用。如果我将它与 toStrictEqual 一起使用,它会起作用。这是一个错误吗?

测试:

test("should update text when typing",() => {
    render(<EditorWindow />);
    userEvent.type(screen.getByRole("textbox"),"bar");
    expect(screen.getByRole("textbox")).toHaveValue(
      expect.stringContaining("bar")
    );
  });

  test("should match text",() => {
    const a = "#title<br>type text here..bar";
    expect(a).toStrictEqual(expect.stringContaining("bar"));
  });

结果:

  <EditorWindow> />
   
    × should update text when typing (46 ms)
    √ should match text

  ● <EditorWindow> /> › should update text when typing

    expect(element).toHaveValue(StringContaining)

    Expected the element to have value:
      StringContaining "bar"
    Received:
      #title<br>type text here..bar

      15 |     render(<EditorWindow />);
      16 |     userEvent.type(screen.getByRole("textbox"),"bar");
    > 17 |     expect(screen.getByRole("textbox")).toHaveValue(
         |                                         ^
      18 |       expect.stringContaining("bar")
      19 |     );
      20 |   });

      at Object.<anonymous> (src/components/EditorWindow.test.tsx:17:41)

我正在使用以下库:

"@testing-library/jest-dom": "^5.11.9","@testing-library/react": "^11.2.5","@testing-library/user-event": "^12.6.3","@types/jest": "^26.0.20","@types/node": "^14.14.25","@types/react": "^17.0.1","@types/react-dom": "^17.0.0",...

希望有人能帮我解决这个问题吗?提前致谢!

解决方法

我设法在没有打字稿警告的情况下获得了工作代码:

 test("should update text when typing",() => {
    render(<EditorWindow />);
    userEvent.type(screen.getByRole("textbox"),"bar");
    const myTextAreaVal = (screen.getByRole("textbox") as HTMLInputElement)
      .value;
    expect(myTextAreaVal.includes("bar")).toBe(true);
  });

我不得不使用类型转换 as HTMLInputElement 以摆脱打字稿警告并能够将文本区域的值存储在变量 myTextAreaVal 中。然后我使用 myTestAreaVal.includes 对字符串进行部分匹配。

感谢 Adrisolid 的提示!

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...