如何在jest和apred-testing-library中模拟document.getElementsbyclassname()?

发布于 2025-02-07 16:31:21 字数 1099 浏览 2 评论 0原文

我们如何模拟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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

苍风燃霜 2025-02-14 16:31:21

不要模拟document.getElementsByClassName()并测试实现细节。而是测试组件的行为,例如组件呈现的内容。

您可以断言是否正确设置了ID HTML属性。

例如

app.tsx

import React from 'react';
import { useEffect } from 'react';

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, i) => {
      return heading.setAttribute('id', `header-toggle-${i}`);
    });
  }, []);

  return (
    <div className="App">
      {numbers.map((num) => {
        return <h1 key={num} className="heading">{num}</h1>;
      })}
    </div>
  );
}

app.test.tsx

import React from 'react';
import { render } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';
import App from './App';

describe('App', () => {
  it('render App', () => {
    const { container } = render(<App />);
    expect(container).toBeInTheDocument();
  });

  it('render App with numbers', () => {
    const { getByText } = render(<App />);
    const numbers = [1, 2, 3, 4, 5, 6];
    numbers.forEach((n, i) => {
      expect(getByText(`${n}`)).toBeInTheDocument();
      expect(getByText(`${n}`).id).toEqual(`header-toggle-${i}`);
    });
  });
});

测试结果:

 PASS  stackoverflow/72626153/App.test.tsx (9.755 s)
  App
    ✓ render App (40 ms)
    ✓ render App with numbers (21 ms)

  console.log
    DO SOMETHING !!

      at stackoverflow/72626153/App.tsx:10:15

  console.log
    DO SOMETHING !!

      at stackoverflow/72626153/App.tsx:10:15

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |     100 |       50 |     100 |     100 |                   
 App.tsx  |     100 |       50 |     100 |     100 | 9                 
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        10.256 s, estimated 11 s
Ran all test suites related to changed files

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:

import React from 'react';
import { useEffect } from 'react';

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, i) => {
      return heading.setAttribute('id', `header-toggle-${i}`);
    });
  }, []);

  return (
    <div className="App">
      {numbers.map((num) => {
        return <h1 key={num} className="heading">{num}</h1>;
      })}
    </div>
  );
}

App.test.tsx:

import React from 'react';
import { render } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';
import App from './App';

describe('App', () => {
  it('render App', () => {
    const { container } = render(<App />);
    expect(container).toBeInTheDocument();
  });

  it('render App with numbers', () => {
    const { getByText } = render(<App />);
    const numbers = [1, 2, 3, 4, 5, 6];
    numbers.forEach((n, i) => {
      expect(getByText(`${n}`)).toBeInTheDocument();
      expect(getByText(`${n}`).id).toEqual(`header-toggle-${i}`);
    });
  });
});

Test result:

 PASS  stackoverflow/72626153/App.test.tsx (9.755 s)
  App
    ✓ render App (40 ms)
    ✓ render App with numbers (21 ms)

  console.log
    DO SOMETHING !!

      at stackoverflow/72626153/App.tsx:10:15

  console.log
    DO SOMETHING !!

      at stackoverflow/72626153/App.tsx:10:15

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |     100 |       50 |     100 |     100 |                   
 App.tsx  |     100 |       50 |     100 |     100 | 9                 
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        10.256 s, estimated 11 s
Ran all test suites related to changed files
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文