Javascript 如何使用反应酶检查实际的 DOM 节点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37723238/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:40:36  来源:igfitidea点击:

how to check the actual DOM node using react enzyme

javascriptdomreactjsenzyme

提问by njorlsaga

Is there a way to get the actual DOM node so I can the query it with the Dom api as opposed to being required to use enzyme's api, it's just for edge cases where for example I need to assert things about the dom node itself.

有没有办法获取实际的 DOM 节点,以便我可以使用 Dom api 查询它,而不是需要使用酶的 api,这仅适用于边缘情况,例如我需要断言有关 dom 节点本身的事情。

回答by tonyjmnz

You can use wrapper.getDOMNode()

您可以使用 wrapper.getDOMNode()

Enzyme docs

酶文档

回答by Tyler Collier

Perhaps you are looking for enzyme's instance()?

也许您正在寻找酶的instance()

const wrapper = mount(<input type="text" defaultValue="hello"/>)
console.log(wrapper.instance().value); // 'hello'

PS:

PS:

instance()should give you a ReactComponent, from which you can use ReactDOM.findDOMNode(ReactComponent) to get a DOMNode. However, when I did that, like the following, it was the exact same object as wrapper.instance():

instance()应该给你一个ReactComponent,从中你可以使用 ReactDOM.findDOMNode(ReactComponent) 来获取一个 DOMNode。但是,当我这样做时,如下所示,它是与 完全相同的对象wrapper.instance()

import ReactDOM from 'react-dom'
const wrapper = mount(<input type="text" defaultValue="sup"/>)
console.log(ReactDOM.findDOMNode(wrapper.instance()) == wrapper.instance()) // true

I don't understand why that is. If you console.log()either one of those, you'll see a HTMLInputElement, but it will contain lots of non-native DOM node looking stuff:

我不明白为什么会这样。如果您console.log()是其中之一,您将看到一个HTMLInputElement,但它会包含许多非本机 DOM 节点外观的东西:

HTMLInputElement {
  '__reactInternalInstance$yt1y6akr6yldi': 
   ReactDOMComponent {
     _currentElement: 
      { '$$typeof': Symbol(react.element),
        type: 'input',
        key: null,
        ref: null,
        props: [Object],
        _owner: [Object],
        _store: {} },

回答by killthrush

I ran into this same problem. In my case, I was testing something built with react-aria-modal, which renders the overlay div in a different part of the DOM than the initial element rendered with mount(). In order to test that this renders properly, I needed to look more globally at the DOM. For this, I used the attachTooption of render()to ensure that my test DOM looks like it should in a real browser. Hereis a good general description of the technique from the docs.

我遇到了同样的问题。就我而言,我正在测试react-aria-modal使用mount(). 为了测试这是否正确呈现,我需要更全面地查看 DOM。为此,我使用了attachTo选项render()来确保我的测试 DOM 在真实浏览器中看起来应该是这样。 是文档中对该技术的很好的一般描述。

Depending on what you need, you can use Tyler Collier's approach for more local parts of the DOM (findDOMNodeusing instance()) or mine for a more global view.

根据您的需要,您可以将 Tyler Collier 的方法用于 DOM 的更多本地部分(findDOMNodeusing instance()),或者使用我的方法来获取更全局的视图。

Here's a sample spec for my use case, showing how to setup/use/teardown the mock DOM:

这是我的用例的示例规范,展示了如何设置/使用/拆卸模拟 DOM:

import MyModalComponent from '../components/my-modal-component'
import React from 'react'
import { jsdom } from 'jsdom'
import { mount } from 'enzyme'

describe('<MyModalComponent /> Component', function(){

  let wrapper

  beforeEach(function(){
    window.document = jsdom('')
    document.body.appendChild(document.createElement('div'))
  })

  afterEach(function(){
    wrapper.detach()
    window.document = jsdom('')
  })

  it('renders the modal closed by default', () => {
    wrapper = mount(
      <MyModalComponent prop1={"foo"}
                        prop2={"bar"}
      />, { attachTo: document.body.firstChild }
    )
    expect(wrapper.html()).to.contain('Content in component')
    expect(document.body.innerHTML).to.not.contain('Content in overlay')
  })

})

回答by Ryan27

If you create a DOM using jsdom, something like this:

如果您使用 jsdom 创建 DOM,则如下所示:

import jsdom from 'jsdom';
const doc = jsdom.jsdom('<!doctype html><html><body></body></html>');
global.document = doc;
global.window = doc.defaultView;

Then you can use enzyme's mount()to render whatever you wish to test.

然后你可以使用酶的mount()来渲染你想要测试的任何东西。

You can then assert against the style you are looking for:

然后,您可以针对您正在寻找的样式进行断言:

expect(wrapper).to.have.style("display", "none");

expect(wrapper).to.have.style("display", "none");

回答by JPRLCol

You can use soemething like :

你可以使用类似的东西:

const dialog = component.find(Modal);
let modal = dialog.node._modal;
modal.getDialogElement().querySelector('#saveBtn')

based on the test for Modal in react-bootstrap web site

基于 react-bootstrap 网站中 Modal 的测试

https://github.com/react-bootstrap/react-bootstrap/blob/master/test/ModalSpec.js

https://github.com/react-bootstrap/react-bootstrap/blob/master/test/ModalSpec.js

回答by Smit

If you want to print out whole DOM,

如果你想打印整个 DOM,

const wrapper = shallow(<MyComponent/>);
console.log("DOM tree for humans", wrapper.text());