DEV Community

Cui Mingda
Cui Mingda

Posted on

How to query element by className in Testing Library

Testing Library默认没有通过className查询元素的方法,但是Web API原生就有啊,我们可以直接通过JavaScript来查询。

比如用CRA创建的项目,在src/App.js中默认会有一个欢迎界面,我们想把它删除,于是先要写一个测试定位这个元素,container返回的就是一个DOM节点,所以直接可以使用querySelector方法来查找子元素,只返回找到的第一个对象,没有找到返回null

describe("Clear default code", () => {
  it("omit header with className App-header", () => {
    const { container } = render(<App />);
    const header = container.querySelector(".App-header");
    expect(header).not.toBeInTheDocument();
  });
});
Enter fullscreen mode Exit fullscreen mode

References

Top comments (0)