加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 资源网站 > 资源 > 正文

测试与reactjs renderIntoDocument由于所需的DOM保持失败

发布时间:2020-12-14 18:49:57 所属栏目:资源 来源:网络整理
导读:我是新来的反应和尝试学习如何测试与它.我遇到了以下测试util方法.但是我仍然收到相同的错误消息:ReferenceError:document未定义. renderIntoDocument ReactComponent renderIntoDocument( ReactElement instance) 将组件渲染到文档中的分离的DOM节点中.此
我是新来的反应和尝试学习如何测试与它.我遇到了以下测试util方法.但是我仍然收到相同的错误消息:ReferenceError:document未定义.

renderIntoDocument

ReactComponent renderIntoDocument(
  ReactElement instance
)

将组件渲染到文档中的分离的DOM节点中.此函数需要一个DOM.

注意:
在导入React之前,您将需要具有全局可用窗口,window.document和window.document.createElement.否则React会认为它无法访问DOM,而像setState这样的方法将无法正常工作.

我知道它失败了DOM的原因,但是如何插入DOM或需要它?

我的测试如下:

import expect from 'expect.js';
import React from 'react';
import Header from '../../components/header';
import {renderShallow} from './help';
import ReactAddOn from 'react/addons';

var TestUtils = ReactAddOn.addons.TestUtils;

describe('Test react',function() {
  let component;

  beforeEach(()=>{
    component = TestUtils.renderIntoDocument(<Header></Header>);
  });


  it('Test if the content been correclty render',function() {
    console.log(component);
  });
});

解决方法

TL;博士;你需要摩萨摩托

根据规格ReactTestUtils#renderIntoDocument,

renderIntoDocument()需要一个DOM:

You will need to have window,window.document and window.document.createElement globally available before you import React. Otherwise React will think it can’t access the DOM and methods like setState won’t work.

传统上,React中的单元测试是使用Jest完成的,它显然包含DOM支持.摩卡不是.

要理解这一点,考虑这个过于简单的比喻,Jest = Mocha jsdom.

jsdom在JavaScript中实现,我们可以使用类似DOM的API来使用,而无需浏览器.这就意味着我们不必像浏览Karma那样捕捉浏览器的顺序(这就是为什么在使用Karma的时候).因此,我们可以在没有浏览器的环境中运行测试,例如在Node或连续集成环境中.

参考文献:

>教程:Testing React on Jsdom
>反应规格:ReactTestUtils#renderIntoDocument
>信息:How to Jest
>信息:react-testing-mocha-jsdom

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读