【问题标题】:Jest react expect.stringcontaining fails in combination with tohavevalueJest react expect.string contains 与 tohavevalue 结合失败
【发布时间】:2021-05-26 22:19:14
【问题描述】:

我尝试在带有 create-react-app 的开玩笑测试脚本中使用 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",
...

希望有人可以帮助我吗?提前致谢!

【问题讨论】:

  • 它对你有用吗? expect(a.includes('bar')).toBe(true)
  • 谢谢,我得到了使用这段代码的测试:test("should update text when typing", () => { render(); userEvent.type(screen.getByRole( "textbox"), "bar"); const myTextAreaVal = screen.getByRole("textbox").value; expect(myTextAreaVal.includes("bar")).toBe(true); });它可以工作,但编译时收到打字稿警告:代码上的类型“HTMLElement”.ts(2339) 上不存在属性“值”:screen.getByRole("textbox").value;

标签: reactjs jestjs babel-jest


【解决方案1】:

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

 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 的提示!

【讨论】:

    猜你喜欢
    • 2019-12-09
    • 1970-01-01
    • 2021-04-04
    • 2016-02-18
    • 2021-12-16
    • 2018-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多