测试覆盖率 React,伊斯坦布尔 -_registerComponent(...):目标容器不是 DOM 元素

2024-02-16

我正在使用 React / Redux / Webpack 编写一个应用程序。我正在使用 karma、mocha 构建测试,并希望使用 istanbul 进行测试覆盖。为了使覆盖范围与业力覆盖范围一起工作,我设置了以下内容karma.config.js

var argv = require('yargs').argv;
var path = require('path');
var webpack = require('webpack');

const PATHS = {
  test: path.join(__dirname, 'test'),
  app: path.join(__dirname, 'app'),
}

module.exports = function(config) {
  config.set({
    // only use PhantomJS for our 'test' browser
    browsers: ['PhantomJS'],

    // just run once by default unless --watch flag is passed
    singleRun: !argv.watch,

    // which karma frameworks do we want integrated
    frameworks: ['mocha', 'chai'],

    // include some polyfills for babel and phantomjs
    files: [
      'node_modules/babel-polyfill/dist/polyfill.js',
      './node_modules/phantomjs-polyfill/bind-polyfill.js',
      // './test/**/*.js', // specify files to watch for tests,
      'test/index.js',
    ],

    preprocessors: {
      // these files we want to be precompiled with webpack
      // also run tests through sourcemap for easier debugging
      // 'test/*.spec.js': ['webpack'],
      'test/index.js': ['webpack', 'sourcemap']
    },

    // A lot of people will reuse the same webpack config that they use
    // in development for karma but remove any production plugins like UglifyJS etc.
    // I chose to just re-write the config so readers can see what it needs to have
    webpack: {
       devtool: 'inline-source-map',
       resolve: {
        // allow us to import components in tests like:
        // import Example from 'components/Example';
        root: PATHS.app,

        // allow us to avoid including extension name
        extensions: ['', '.js', '.jsx'],

        // required for enzyme to work properly
        alias: {
          'sinon': 'sinon/pkg/sinon'
        }
      },
      module: {
        // don't run babel-loader through the sinon module
        noParse: [
          /node_modules\/sinon\//
        ],
        preLoaders: [
            // instrument only testing sources with Istanbul
            // {
            //     test: /\.js$/,
            //     include: path.resolve('app/'),
            //     exclude: /node_modules/,
            //     loader: 'istanbul-instrumenter'
            // }
            {
              test: /\.jsx?$/,
              exclude: [/node_modules/, /test/],
              loader: 'isparta-instrumenter-loader'
            },
        ],

        // run babel loader for our tests
        loaders: [
          {
            test: /\.css$/,
            loader: 'style!css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]'
          },
          {
            test: /\.jsx?$/,
            loader: 'babel',
            exclude: /node_modules/,
            query: {
              presets: ['es2015', 'react', 'survivejs-kanban']
            }
          },
        ],
      },
      // required for enzyme to work properly
      externals: {
        'jsdom': 'window',
        'cheerio': 'window',
        'react/lib/ExecutionEnvironment': true,
        'react/lib/ReactContext': 'window'
      },
    },
    // displays tests in a nice readable format
    reporters: ['spec', 'coverage'],
    webpackMiddleware: {
      noInfo: true
    },
    // tell karma all the plugins we're going to be using to prevent warnings
    plugins: [
      'karma-mocha',
      'karma-chai',
      'karma-webpack',
      'karma-phantomjs-launcher',
      'karma-spec-reporter',
      'karma-sourcemap-loader',
      'karma-coverage'
    ]
  });
};

业力的入口点只是test/index.js。看起来像这样

// require all the tests so they will run.
const testsContext = require.context('.', true, /spec/);
testsContext.keys().forEach(testsContext);

// require all the .js and .jsx files in app so they will be included in coverage
const componentsContext = require.context('../app/', true, /jsx?$/);

//  Date: April 16 2016
//  Author: Benjamin Conant
//  componentsContext.keys() is an array that includes file paths for all the 
//  .js and .jsx files in ./app .... karma fails with
//  PhantomJS 2.1.1 (Mac OS X 0.0.0) ERROR
//  Invariant Violation: _registerComponent(...): Target container is not a DOM element.
//  at /Users/benconant/Dev/MyFin/my-fin-front-end/test/index.js:15283 <- webpack:///~/react/~/fbjs/lib/invariant.js:45:0
//  if the entry point index.jsx file is included. Seems to have somthing
//  to do with trying to actually write to the DOM. So, I filter out index.jsx and the tests run very well.
//  This means that we will probubly not be able to test index.jsx until this is solved.

let componentsContextKeysWithoutIndexJsx = componentsContext.keys().filter(function (filePath) { return filePath !== './index.jsx' });
componentsContextKeysWithoutIndexJsx.forEach(componentsContext);
// componentsContext.keys().forEach(componentsContext); --- the way it should be if we did not have to remove ./index.jsx

正如您从注明日期的评论中看到的那样。如果index.jsx包括在内,当我运行测试时,我得到......

PhantomJS 2.1.1 (Mac OS X 0.0.0) ERROR
  Invariant Violation: _registerComponent(...): Target container is not a DOM element.
  at /Users/benconant/Dev/MyFin/my-fin-front-end/test/index.js:15283 <- webpack:///~/react/~/fbjs/lib/invariant.js:45:0

这是我的index.jsx以供参考

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';;
import { createStore, combineReducers, applyMiddleware } from 'redux';
import { Router, Route, Link, browserHistory, hashHistory, IndexRoute } from 'react-router';
import { syncHistoryWithStore, routerReducer } from 'react-router-redux';

import injectTapEventPlugin from 'react-tap-event-plugin';
injectTapEventPlugin();


import configureStore from './store/configureStore';
import todoApp from './reducers';
import App from './containers/app/App';
import IntroSlides from './containers/IntroSlides';
import LandingPage from './containers/LandingPage';

let store = configureStore();

const history = process.env.HASH_ROUTING ? syncHistoryWithStore(hashHistory, store) : syncHistoryWithStore(browserHistory, store);


ReactDOM.render(
  <Provider store={store}>
     <Router history={history}>
      <Route path="/" component={App}>
        <IndexRoute component={LandingPage} />
        <Route path="intro" component={IntroSlides}/>
      </Route>
    </Router>
  </Provider>,
  document.getElementById('app')
)

我进入 React 生态系统大约一周了,所以几乎肯定我在做一些愚蠢的事情,但这已经花费了很多时间,非常感谢您的帮助!


我也遇到了同样的问题,在我的例子中,这是因为 React 找不到需要渲染 html 的元素。

我找到了一个快速修复方法,将以下 if 语句添加到我的主 js 文件中:

if ($('#app').length <= 0) {
  $('body').prepend('<div id="app"></div>');
}

ReactDom.render(
  <App />,
  document.getElementById('app')
);

我知道这一定不是解决问题的最佳方法,但至少目前有效。如果有人知道更好的方法,请告诉我们!

我还在您的评论中提到的线程上发布了此解决方案。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

测试覆盖率 React,伊斯坦布尔 -_registerComponent(...):目标容器不是 DOM 元素 的相关文章

  • Javascript - 在加载所有图像后执行

    看了别人的问题我想 window onload 会回答我的问题 我已经尝试过这个 但它会在页面加载时立即执行代码 而不是在图像加载之后 如果有什么区别的话 图像来自 CDN 并且不是相对的 有人知道解决办法吗 我没有使用 jQuery 想要
  • 在 javascript、jQuery 或 css 中,如何让 div 或 iframe 展开以填充其余空间

    我有三个 iframe 我将顶部 iframe 设置为 50px 高度 将底部 iframe 设置为 50px 但我希望中间 iframe 扩展以填充其余空间 有没有一种技术可以用来对任何窗口屏幕尺寸执行此操作 谢谢 example
  • Jest - 模拟函数,从另一个文件导入

    测试的文件使用从另一个文件导入的函数 import myFunc from myFile 如何在该文件的测试中模拟该函数的返回值 我正在使用笑话 这对我有用 我不确定这是否是一个好的做法 import as myFile from myFi
  • Web 组件 - 服务/非 html 组件

    所以我来自 Angular 想看看如何创建vanilla Web components 现在 从 Angular 开始 我们倾向于将事物分开 组件 充当 HTML CSS 和一些 javascript 然后是 服务 主要负责收集数据和执行不
  • 启用/禁用由用户输入确定的复选框

    我有一个简单的表单 用户可以在其中输入他的联系号码 如果联系号码以 07 开头 则该复选框已启用 其他我需要禁用它的复选框 我已经编写了一些代码 但我面临的问题是 当用户键入 01 时 它会被禁用 但如果他们继续在 01 之后添加任何其他数
  • 如何动态突出显示网页上的字符串?

    我想创建带有 url 的页面 例如 http xyzcorp schedules 2015Aug24 Aug28 Jim Hawkins http xyzcorp schedules 2015Aug24 Aug28 Billy Bones
  • 使用文件 API 将资源加载到 Three.js 中

    我想创建导入 3D 模型以在浏览器中查看的功能 方法是使用File API http www html5rocks com en tutorials file dndfiles Three js 加载器在我托管的文件上运行良好 我的理解是加
  • 使用 JavaScript 生成 PDF 文件

    我正在尝试将 XML 数据从网页转换为 PDF 文件 并且希望能够完全在 JavaScript 中完成此操作 我需要能够绘制文本 图像和简单的形状 我希望能够完全在浏览器中完成此操作 我刚刚写了一个名为jsPDF https github
  • 在 jQuery 可排序中对多个选定项目进行排序?

    我试图在 jQuery 可排序集中选择多个项目 然后将选定的项目一起移动 这是我的弱点开始尝试使其发挥作用 http jsfiddle net benstenson CgD8Y 这是代码 HTML div class container d
  • ToggleClass 动画 jQuery?

    我的网站上有一个部分 当用户单击时我希望它展开 我正在使用 jQuerytoggleClass为了这 expandable function e e preventDefault this closest article toggleCla
  • 为什么 Web Worker 性能在 30 秒后急剧下降?

    我正在尝试提高在网络工作人员中执行时脚本的性能 它旨在解析浏览器中的大型文本文件而不会崩溃 一切都运行得很好 但我注意到使用网络工作者时大文件的性能存在严重差异 于是我做了一个简单的实验 我在同一输入上运行脚本两次 第一次运行在页面的主线程
  • 为什么将 x 和 y 设置为 0 时 svg 文本会消失?

    我刚刚开始阅读有关svg我提出了以下问题 我正在创建一个简单的svg with a text里面如下图所示 从我的阅读中我了解到x and y of the text标签声明文本在标签内的位置svg space 为什么当我同时设置x and
  • 如何使用 vanilla JS 实现可维护的反应式 UI

    今天我遇到了一个问题 可以通过使用像 Vue 这样的反应式和状态管理框架来轻松解决 遗憾的是 无法使用它 以下 简化 情况 链接到代码笔 https codepen io theiaz pen BazErKV 我们有一个服务器渲染的页面 其
  • 如何打开弹出窗口并用父窗口中的数据填充它?

    如何使用 JavaScript jQuery 使用父页面中 JS 变量的数据填充弹出窗口 在我的示例中 我有一个文件名数组 我在父窗口中最多列出五个 如果还有更多 我想提供一个链接来打开弹出窗口并列出数组中的每个帖子 因此 如果我打开一个包
  • 如何在 ASP.NET MVC 3 的 Razor 视图中编码嵌入的 javascript?

    如何在以下上下文中正确编码 JavaScript 我的 JSON 对象中的值是由应用程序管理员设置的 因此我假设它们需要正确编码 对于 HTML 和 JavaScript 都是如此 我在用着System Web Script Seriali
  • Ember Data 中出现“超出最大调用堆栈大小”错误的原因可能是什么?

    Ember 发布新版本 3 6 0 后 我开始在控制台中收到错误 rsvp js 24 未捕获 RangeError 超出最大调用堆栈大小 在 WeakMap get 在 getCacheFor metal js 25 在 Computed
  • JavaScript 数组扩展语法的时间复杂度是多少?

    我想知道在 JavaScript 中使用数组扩展的时间复杂度是多少 是线性 O n 还是常数 O 1 下面的语法示例 let lar Math max nums 传播称为 Symbol iterator 有关对象的属性 对于数组 这将迭代数
  • Flowtype 属性“msg”缺失为 null 或未定义

    我发现 Flow 很难用 我明白那个Array find可以返回或未定义 因此 通过阅读以下内容 github Array find on Array 引发 https github com facebook flow issues 351
  • Internet Explorer 9 是否会因数组和对象文字末尾的额外逗号而卡住?

    现代浏览器和 Node js 等环境允许您说 a 1 b 2 或 1 2 3 这在历史上一直是 Internet Explorer 的问题 Internet Explorer 9 中修复了此问题吗 对此有两种不同的答案 一种是对象初始值设定
  • 无法使用 HTML 设置未定义 jQuery UI 自动完成的属性“_renderItem”

    我使用以下代码将 jQuery UI 自动完成项呈现为 HTML 这些项目在自动完成控件中正确呈现 但我不断收到此 JavaScript 错误并且无法移动过去 Firefox 无法转换 JavaScript 参数 Chrome 无法设置未定

随机推荐