简体   繁体   English

单元测试:如何在反应中模拟 document.getElementById()?

[英]Unit Test: How to mock document.getElementById() in react?

I want to test following code with jest.我想用玩笑测试以下代码。

Does anynoe know how to mock document.getElementById() ?有人知道如何模拟document.getElementById()吗?

if (document.getElementById('estateList')) {
    render(
        <Provider store={store}>
            <EstateList />
        </Provider>,
        window.document.getElementById('estateList')
    );
}


if (document.getElementById('articleList')) {
    render(
        <Provider store={store}>
            <ArticleList />
        </Provider>,
        window.document.getElementById('articleList')
    );
}

if (document.getElementById('articleDetail')) {
    render(
        <Provider store={store}>
            <ArticleDetail />
        </Provider>,
        window.document.getElementById('articleDetail')
    );
}

I think I can put render inside a function, like:我想我可以把渲染放在一个函数中,比如:

function estateList() {
    render(
        <Provider store={store}>
            <EstateList />
        </Provider>,
        window.document.getElementById('estateList')

    );
}

Then simply test estateList(), without mocking document.getElementById() , but is there anyway to mock document.getElementById() ?然后简单地测试estateList(),无嘲讽的document.getElementById(),但反正是有嘲笑的document.getElementById()?

Using jest.fn(implementation) create mocked getElementById method and replace the method on document .使用jest.fn(implementation)创建模拟的getElementById方法并替换document上的方法。

Eg例如

index.tsx : index.tsx

import React from 'react';
import { Provider } from 'react-redux';
import { render } from 'react-dom';
import { createStore } from 'redux';

export const store = createStore(() => 0);

export const EstateList = () => <div>EstateList</div>;
export const ArticleList = () => <div>ArticleList</div>;
export const ArticleDetail = () => <div>ArticleDetail</div>;

function bootstrap() {
  if (document.getElementById('estateList')) {
    render(
      <Provider store={store}>
        <EstateList />
      </Provider>,
      window.document.getElementById('estateList'),
    );
  }

  if (document.getElementById('articleList')) {
    render(
      <Provider store={store}>
        <ArticleList />
      </Provider>,
      window.document.getElementById('articleList'),
    );
  }

  if (document.getElementById('articleDetail')) {
    render(
      <Provider store={store}>
        <ArticleDetail />
      </Provider>,
      window.document.getElementById('articleDetail'),
    );
  }
}

export { bootstrap };

index.test.tsx : index.test.tsx

import React from 'react';
import { render } from 'react-dom';
import { bootstrap, store, EstateList, ArticleList, ArticleDetail } from './';
import { Provider } from 'react-redux';

jest.mock('react-dom');
const mockedRender = render as jest.Mocked<typeof render>;

describe('49146453', () => {
  let oGetElementById;
  beforeAll(() => {
    oGetElementById = document.getElementById;
  });
  afterAll(() => {
    document.getElementById = oGetElementById;
  });
  it('should render estatelist', () => {
    document.getElementById = jest.fn().mockImplementation((id) => (id === 'estateList' ? 'estateList-dom' : null));
    bootstrap();
    expect(mockedRender).toBeCalledWith(
      <Provider store={store}>
        <EstateList />
      </Provider>,
      'estateList-dom',
    );
  });

  it('should render articleList', () => {
    document.getElementById = jest.fn().mockImplementation((id) => (id === 'articleList' ? 'articleList-dom' : null));
    bootstrap();
    expect(mockedRender).toBeCalledWith(
      <Provider store={store}>
        <ArticleList />
      </Provider>,
      'articleList-dom',
    );
  });

  it('should render articleDetail', () => {
    document.getElementById = jest.fn().mockImplementation((id) => (id === 'articleDetail' ? 'articleDetail-dom' : null));
    bootstrap();
    expect(mockedRender).toBeCalledWith(
      <Provider store={store}>
        <ArticleDetail />
      </Provider>,
      'articleDetail-dom',
    );
  });
});

unit test result with coverage report:带有覆盖率报告的单元测试结果:

 PASS  src/stackoverflow/49146453/index.test.tsx
  49146453
    ✓ should render estatelist (6ms)
    ✓ should render articleList (1ms)
    ✓ should render articleDetail (1ms)

-----------|----------|----------|----------|----------|-------------------|
File       |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
-----------|----------|----------|----------|----------|-------------------|
All files  |    84.21 |      100 |       40 |      100 |                   |
 index.tsx |    84.21 |      100 |       40 |      100 |                   |
-----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       3 passed, 3 total
Snapshots:   0 total
Time:        5.618s, estimated 11s

The version about jest.js and related packages, check source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/49146453 jest.js及相关包的版本,查看源码: https : //github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/49146453

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 Gatsby(React) 中实现 document.getElementById - How to implement document.getElementById in Gatsby(React) 如何在 React 测试用例中使用 document.getElementById() (JEST+ ENZYME) - How to use document.getElementById() in React Test cases (JEST+ ENZYME) 如何减少Document.getelementbyid - How to reduce Document.getelementbyid 如何使用document.getElementById - How to use of document.getElementById 如何在反应中将 document.getElementById() 与样式组件一起使用? - How to use document.getElementById() with styled components in react? 反应如何设置组件ID以能够使用document.getElementById() - React how to set component id to be able to use document.getElementById() document.getElementById(“test”)。value和document.getElementById(“test”)之间的区别是什么.internalHTML - What's the difference between document.getElementById(“test”).value and document.getElementById(“test”).innerHTML document.getElementByID(&quot;test&quot;).innerHTML 给出 TypeError: &#39;undefined&#39; is not a function (evaluating &#39;document.getElementByID(&quot;test&quot;)&#39;) - document.getElementByID(“test”).innerHTML giving TypeError: 'undefined' is not a function (evaluating 'document.getElementByID(“test”)') 为什么我的酶快照测试React在document.getElementById()调用失败? - Why does my enzyme snapshot test of React fail on a document.getElementById() call? 如何使用document.getElementById打印id get? - How to print an id get with document.getElementById?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM