如何在jest和apred-testing-library中模拟document.getElementsbyclassname()?
我们如何模拟document.getElementsByClassNames()在jest/ react-testing-library中,因为代码的这些部分未涵盖代码覆盖
import { useEffect } from "react";
import "./styles.css";
const numbers = [1, 2, 3, 4, 5, 6];
export default function App() {
useEffect(() => {
const headings = [...document.getElementsByClassName("heading")];
if(!!headings.length){
console.log("DO SOMETHING !!")
}
headings?.map((heading) => {
return heading.setAttribute("id", "header-toggle");
});
}, []);
return (
<div className="App">
{numbers?.map((num) => {
return <h1 className="heading">{num}</h1>;
})}
</div>
);
}
app.test.js
import React from 'react';
import { render, cleanup } from '@testing-library/react';
import App from './App'
afterEach(cleanup);
it('render App', () => {
document.getElementsByClassName() = jest.fn().mockImplementation([{setAttribute:jest.fn()}])
const { container } = render(<App/>);
expect(container).toBeInTheDocument()
});
How can we mock document.getElementsByClassNames() in jest/ react-testing-library , since these part of the code is not been covered in code-coverage
import { useEffect } from "react";
import "./styles.css";
const numbers = [1, 2, 3, 4, 5, 6];
export default function App() {
useEffect(() => {
const headings = [...document.getElementsByClassName("heading")];
if(!!headings.length){
console.log("DO SOMETHING !!")
}
headings?.map((heading) => {
return heading.setAttribute("id", "header-toggle");
});
}, []);
return (
<div className="App">
{numbers?.map((num) => {
return <h1 className="heading">{num}</h1>;
})}
</div>
);
}
App.test.js
import React from 'react';
import { render, cleanup } from '@testing-library/react';
import App from './App'
afterEach(cleanup);
it('render App', () => {
document.getElementsByClassName() = jest.fn().mockImplementation([{setAttribute:jest.fn()}])
const { container } = render(<App/>);
expect(container).toBeInTheDocument()
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不要模拟
document.getElementsByClassName()
并测试实现细节。而是测试组件的行为,例如组件呈现的内容。您可以断言是否正确设置了
ID
HTML属性。例如
app.tsx
:app.test.tsx
:测试结果:
Don't mock
document.getElementsByClassName()
and test the implementation detail. Instead, test the component's behavior such as what the component renders.You can assert if the
id
HTML attribute is set correctly or not.E.g.
App.tsx
:App.test.tsx
:Test result: