GVKun编程网logo

由于Webpack中的CSS,Mocha测试失败(由于web服务器上的isapi和cgi限制)

16

本文将介绍由于Webpack中的CSS,Mocha测试失败的详细情况,特别是关于由于web服务器上的isapi和cgi限制的相关信息。我们将通过案例分析、数据研究等多种方式,帮助您更全面地了解这个主题

本文将介绍由于Webpack中的CSS,Mocha测试失败的详细情况,特别是关于由于web服务器上的isapi和cgi限制的相关信息。我们将通过案例分析、数据研究等多种方式,帮助您更全面地了解这个主题,同时也将涉及一些关于#单元测试#以karma+mocha+chai 为测试框架的Vue webpack项目(二)、05webpack中html-webpack-plugin的2个作用、css – 在webpack中使用本地Web字体、karma+mocha+webpack3 搭建 vue2 单元测试环境的知识。

本文目录一览:

由于Webpack中的CSS,Mocha测试失败(由于web服务器上的isapi和cgi限制)

由于Webpack中的CSS,Mocha测试失败(由于web服务器上的isapi和cgi限制)

我是Mocha的新手,我正试图用它来测试一个简单的React组件。如果react组件没有任何CSS样式,则测试将通过,但是如果React组件内的标签包含任何className,则会引发语法错误:

Testing.react.js

import React from ''react'';export default class Testing extends React.Component {  render() {    return (      <section>        <form>          <input type="text" />        </form>      </section>    );  }}

testing.jsx

import {  React,  sinon,  assert,  expect,  TestUtils} from ''../../test_helper'';import TestingSample from ''../../../app/components/Testing.react.js'';describe(''TestingSample component'', function(){    before(''render and locate element'', function(){        var renderedComponent = TestUtils.renderIntoDocument(            <TestingSample />        );        var inputComponent = TestUtils.findRenderedDOMComponentWithTag(            renderedComponent, ''input''        );        this.inputElement = inputComponent.getDOMNode();    });    it(''<input> should be of type "text"'', function () {        assert(this.inputElement.getAttribute(''type'') === ''text'');    });})

测试将通过:

> mocha --opts ./test/javascripts/mocha.opts --compilers js:babel/register --recursive test/javascripts/**/*.jsx  TestSample component    ✓ <input> should be of type "text"  1 passing (44ms)

在输入标签内添加className之后,出现错误:

import React from ''react'';import testingStyle from ''../../scss/components/landing/testing.scss'';export default class Testing extends React.Component {  render() {    return (      <section>        <form>          <input type="text" className="testingStyle.color" placeholder="Where would you like to dine" />             </form>      </section>    );  }}

测试结果:

SyntaxError: /Users/../../../Documents/project/app/scss/components/landing/testing.scss: Unexpected token (1:0)> 1 | .color {    | ^  2 |   color: red;  3 | }

我已经在网上搜索过,但到目前为止还没有运气。我想念什么吗?请帮助我或指出正确的方向,将不胜感激。我当前正在使用:
Node Express Server
React
React-router
Webpack
Babel
Mocha
Chai
Sinon
Sinon-Chai

答案1

小编典典

有一个babel/register样式挂钩可以忽略样式导入:

https://www.npmjs.com/package/ignore-
styles

安装它:

npm install --save-dev ignore-styles

运行没有样式的测试:

mocha --require ignore-styles

#单元测试#以karma+mocha+chai 为测试框架的Vue webpack项目(二)

#单元测试#以karma+mocha+chai 为测试框架的Vue webpack项目(二)

学习对vue组件进行单元测试,先参照官网编写组件和测试脚本。

 

1、简单的组件

组件无依赖,无props

对于无需导入任何依赖,也没有props的,直接编写测试案例即可。

/src/testSrc/simpleComp.vue

<template>
  <span>{{ message }}</span>
</template>

<script>
  export default {
    data () {
      return {
        message: ''hello!''
      }
    },
    created () {
      this.message = ''bye!''
    }
  }
</script>

 

/test/unit/specs/simpleComp.secs.js

import Vue from ''vue''
import simpleComp from ''@/testSrc/simpleComp.vue''

describe(''simpleComp'', () => {
  // 检查原始组件选项
  it(''has a created hook'', () => {
    expect(typeof simpleComp.created).to.eql(''function'')
  })

  // 评估原始组件选项中的函数结果
  it(''sets the correct default data'', () => {
    expect(typeof simpleComp.data).to.eql(''function'')
    const defaultData = simpleComp.data()
    expect(defaultData.message).to.eql(''hello!'')
  })

  // 检查 mount 中的组建实例
  it(''correctly sets the message when created'', () => {
    const vm = new Vue(simpleComp).$mount()
    expect(vm.message).to.eql(''bye!'')
  })

  // 创建一个实例并检查渲染输出
  it(''renders the correct message'', () => {
    const Constructor = Vue.extend(simpleComp)
    const vm = new Constructor().$mount()
    expect(vm.$el.textContent).to.eql(''bye!'')
  })
})

 describe('''', () => {// describe块

  it('''', () => {  //一个it块代表一个测试用例

  })

      // 多个it块构成了test suite【测试套件】

   })

 我在测试的时候是一个it块一个it块的增加,每编写完成一个it块,就保存并查看【#karma start】监控的运行结果。大概就是webpack compile 成功与否,测试用例在各浏览器的运行情况,代码覆盖率总结报告。

     

     这里应该是 8 SUCCESS, 忘记截图了。Statements表示“声明”,Branches表示分支,Functions表示方法,Lines表示行的覆盖率。 

 

2、有入参的组件

组件有props

对于组件需要props,编写单元测试时,通过propsData传递该参数。

/src/testSrc/propComp.vue

<template>
  <p>{{ msg }}</p>
</template>

<script>
  export default {
    props: [''msg'']
  }
</script>

  

/test/unit/specs/propComp.specs.js

/**
 * 组件需要 props 时,通过 propsData 传递该参数
 */
import Vue from ''vue''
import propComp from ''@/testSrc/propComp.vue''

function getRenderedText (Component, propsDataMsg) {
  const Ctor = Vue.extend(Component)
  const vm = new Ctor({ propsData: propsDataMsg }).$mount()
  return vm.$el.textContent
}

describe(''propComp'', () => {
  it(''renders correctly with different props'', () => {
    expect(getRenderedText(propComp, {
      msg: ''Hello''
    })).to.eql(''Hello'')

    expect(getRenderedText(propComp, {
      msg: ''Bye''
    })).to.eql(''Bye'')
  })
})

 

3、有依赖其他组件的组件【TODO-->未解决,会报错还没理解】

若组件存在依赖,则可通过inject-loader解决。inject-loader可将任意依赖项注入到*.vue组件中。

/src/testSrc/dependencyComp.vue

<template>
  <div>
    {{ msg }}
  </div>
</template>

<script>
  // this dependency needs to be mocked
  import SomeService from ''../service''

  export default {
    data () {
      return {
        msg: SomeService.msg
      }
    }
  }
</script>

/test/unit/specs/dependencyComp.specs.js

import Vue from ''vue''

// "!!"表示禁用全局配置的所有loaders。“vue-loader?inject!”表示使用vue-loader,传入inject参数
const ExampleInjector = require(''!!vue-loader?inject!./example.vue'')
// 运行ExampleInjector函数返回一个denpendencyComp的实例,该实例中denpendencyComp组件的依赖项已被模拟
const ExampleWithMocks = ExampleInjector({
  // mock it
  ''../service'': {
    msg: ''Hello from a mocked service!''
  }
})

describe(''dependencyComp'', () => {
  it(''should render'', () => {
    const vm = new Vue({
      template: ''<div><test></test></div>'',
      components: {
        ''test'': ExampleWithMocks
      }
    }).$mount()

    expect(vm.$el.querySelector(''.msg'').textContent).to.eql(''Hello from a mocked service!'')
  })
})

 

4、有异步操作的组件

对于异步操作,it块执行的时候,需要传入一个回调函数,通常该函数被命名为done。当测试结束的时候,必须显式调用这个函数【done()】,告诉Mocha测试结束了。否则,Mocha就无法知道,测试是否结束,会一直等到超时报错。

就用之前编写的简单的组件,增加测试用例 —— it块就行了。

/src/testSrc/simpleComp.vue

【见1、简单的组件

 

更新 /test/unit/specs/simpleComp.specs.js

// 新增一个it块
// 异步操作:在状态更新后检查生成的 HTML
it(''updates the rendered message when vm.message updates'', done => {
  const vm = new Vue(simpleComp).$mount()
  vm.message = ''foo''
  // 在状态改变后和断言 DOM 更新前等待一刻
  Vue.nextTick(() => {
    expect(vm.$el.textContent).to.eql(''foo'')
    done()   //显示调用结束函数done(),告诉mocha异步操作结束
  })
})

#karma start

  

实际上总共只有7个测试用例(即7个it块),但是我配置浏览器的时候配置了两个(Chrome、FireFox),每个而是用例都会在它们两个浏览器运行,故而总共运行了14个。  

 

资料:

1、Vue单元测试---Karma+Mocha+Chai实践

 

05webpack中html-webpack-plugin的2个作用

05webpack中html-webpack-plugin的2个作用

  <!-- 15  html-webpack-plugin的2个作用
     下载 cnpm i html-webpack-plugin -D   作用在==>内存中生成页面
可以在package.json中去查看是否有 在webpack中 导入在内存中生成的HTML页面的插件
// 只要是webpack的插件 都要放入 plugins 这个数组中去 const htmlwebpackPlugin=require("html-webpack-plugin") plugins: [ new webpack.HotModuleReplacementPlugin(),这是热跟新的配置 new htmlwebpackPlugin({ 创建一个 在内存中生成 HTML页面的插件 template:path.join(__dirname,'./src/index.html'),1)">指定模板页面,将来会根据指定的页面路径,去生成内存中的 页面 filename:"index.html" 指定生成的页面名称 }) ] // 当我们使用html-webpack-plugin之后,我们不需要手动处理bundle.js的引用路径, (我们可以将index.html中的 <script src="../dist/bundle.js"></script>注释掉 ) 因为这个插件,已经帮我们自动创建一个 合适的script,并且引用了正确的路径 这个插件有两个作用的 在内存中帮我们生成一个页面 帮我们自动创建一个合适的script标签 并且引入正确的路径

运行的命令 npm run dev

 

完整代码

 package.json

{
  "devDependencies": {
    "html-webpack-plugin": "^4.5.0",
    "webpack": "^4.44.2",
    "webpack-cli": "^3.3.12",
    "webpack-dev-server": "^3.11.0"
  },
  "scripts": {
    "dev": "webpack-dev-server --open --port 3000 --contentBase src --hot"
  },
  "dependencies": {
    "jquery": "^3.5.1"
  }
}

 

src下的main.js

import $ from "jquery";
$(function () {
  console.log("我是重新删除了哈");
  console.log("哈在手我的删除动阀案说现在辞职 法十分哈儿");
});

 

webpack.config.js

const path = require("path");
const htmlwebpackPlugin = require("html-webpack-plugin");
var webpack = require("webpack");
module.exports = {
  entry: path.join(__dirname, "./src/main.js"), //入口文件 使用webpack要打包哪一个文件
  output: {
    //输出相关的配置
    path: path.join(__dirname, "./dist"), //指定打包好的文件会输出到哪一个目录(dist)下去
    filename: "testindex.js", //指定打包好的文件的名称叫什么名字
  },
 
  plugins: [
    new webpack.HotModuleReplacementPlugin(), //这是热跟新的配置

    new htmlwebpackPlugin({
      //创建一个 在内存中生成 HTML页面的插件
      template: path.join(__dirname, "./src/index.html"), //指定模板页面,将来会根据指定的页面路径,去生成内存中的 页面
      filename: "index.html", //指定生成的页面名称
    }),
  ],
};

 

src下的index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <Meta charset="UTF-8">
    <Meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <!-- <script src="/testindex.js"></script>   注释了--> 
</head>

<body>
 
    <div>12</div>
    <div>222</div>
    <div>222</div>
</body>
</html>
 

 

css – 在webpack中使用本地Web字体

css – 在webpack中使用本地Web字体

我正在尝试在我的React项目中使用一些本地Web字体.我将它们包含在我的main.scss文件中,并通过webpack加载它们.捆绑包构建正确,包括main.scss样式.我看到webpack加载了字体文件,并将它们复制到public / fonts /,但我的bundle文件找不到字体.

据我了解,你的@ font-face src应该与bundle的位置有关.我将此设置为与在webpack中加载字体的路径相同,’./ fonts /’.我看到的确切错误是:

file:///Users/myusername/Documents/folder1/folder2/folder3/APP/fonts/FoundersGroteskWeb-Regular.woff net::ERR_FILE_NOT_FOUND

我一直在尝试很多不同的路径配置,并且在webpack中使用了publicPath选项,但是我现在正在围绕看起来非常简单的引用错误.

文件结构:

APP
├──webpack.config.js
├──src
     ├──app
        ├──App.jsx
        ├──styles
           ├──main.scss
           ├──fonts
              ├──allthefonts.woff
     ├──public
        ├──bundle.js
        ├──fonts
           ├──allthefonts.woff

App.jsx:

require('./styles/main.scss');

main.scss:

@font-face {
    font-family: FoundersGrotesk;
    src: url('./fonts/FoundersGroteskWeb-Bold.eot') format('eot'),url('./fonts/FoundersGroteskWeb-Bold.woff') format('woff'),url('./fonts/FoundersGroteskWeb-Bold.woff2') format('woff2');
    font-weight: bold;
}

@font-face {
    font-family: FoundersGrotesk_Cnd;
    src: url('./fonts/FoundersGrotXCondWeb-Bold.eot') format('eot'),url('./fonts/FoundersGrotXCondWeb-Bold.woff') format('woff'),url('./fonts/FoundersGrotXCondWeb-Bold.woff2') format('woff2');
    font-weight: bold;
}

@font-face {
    font-family: FoundersGrotesk;
    src: url('./fonts/FoundersGroteskWeb-Regular.eot') format('eot'),url('./fonts/FoundersGroteskWeb-Regular.woff') format('woff'),url('./fonts/FoundersGroteskWeb-Regular.woff2') format('woff2');
    font-weight: normal;
}

webpack.config.js:

'use strict';

const webpack = require('webpack');
const PROD = JSON.parse(process.env.PROD_ENV || '0');

module.exports = {

  entry: './src/app/App.jsx',output: {
    path: './src/public/',filename: PROD ? 'bundle.min.js' : 'bundle.js'
  },module: {
    loaders: [
      {
        test: /\.jsx?$/,loader: 'babel-loader',exclude: '/node_modules/',query: {
          presets: ['es2015','react','stage-1']
        }
      },{
        test: /\.s?css$/,loaders: ['style','css','sass']
      },{
        test: /\.(eot|svg|ttf|woff|woff2)$/,loader: 'file-loader?name=./fonts/[name].[ext]'
      }
    ]
  }
};

解决方法

得益于@omerts在 this thread中获得了一个有效的解决方案.解决方案涉及使用publicPath.我一直试图用它作为module.exports中的一个选项,使用字体文件加载器,而不是输出.

更新了webpack.config.js:

const webpack = require('webpack');
const PROD = JSON.parse(process.env.PROD_ENV || '0');
const path = require('path');

const PATHS = {
  build: path.join(__dirname,'./src/public')
};

module.exports = {

  entry: './src/app/App.jsx',output: {
    path: PATHS.build,filename: PROD ? 'bundle.min.js' : 'bundle.js',publicPath: PATHS.build
  },loader: 'file-loader?name=/fonts/[name].[ext]'
      },{
        test: /\.(jpg|png)$/,loader: 'file-loader?name=/fonts/[name].[ext]'
      }
    ]
  },plugins: PROD ? [
    new webpack.optimize.UglifyJsPlugin({
      beautify: false,comments: false,compress: { 
        warnings: false,drop_console: true
      },mangle: {
        except: ['$'],screw_ie8: true,keep_fnames: false
      }
    })
  ] : []
};

karma+mocha+webpack3 搭建 vue2 单元测试环境

karma+mocha+webpack3 搭建 vue2 单元测试环境

这里我记录下搭建基于 karma+mocha+webpack3+vue2 的测试环境。因为之前折腾了一段时间,发现的坑挺深的,防止后面再次掉进坑里,留个笔记。如果这边文章能解决大家遇到的问题那就更好了?

1、需要安装哪些包

以下列出来的包安装在项目中即可,还有几个包需要全局安装:
babel、mocha、karma

babel 相关的:

  • babel-core
  • babel-plugin-syntax-jsx // 支持 jsx 语法
  • babel-plugin-transform-runtime // 描述太晦涩, 官方文档: https://github.com/babel/babe...
  • babel-plugin-transform-vue-jsx // 支持 vue2.x jsx 语法
  • babel-preset-env // 可以根据您所支持的环境自动确定您需要的Babel插件和polyfills(.babelrc 配置)
  • babel-preset-es2015
  • babel-preset-stage-2
  • babel-runtime
  • babel-polyfill // 支持老版本浏览器

karma、mocha、断言 包

  • karma
  • mocha
  • chai // BDD 、TDD 断言框架
  • chalk // 终端里可以给输出内容添加颜色
  • karma-mocha
  • karma-coverage // 生成代码覆盖率
  • karma-phantomjs-launcher // phantomjs 启动器
  • karma-phantomjs-shim // 可以支持 phantomjs 默认不支持的功能,如 Object.assign 等...
  • karma-sinon-chai
  • karma-spec-reporter // 终端里输出测试结果
  • karma-webpack // karma 支持 webpack 插件,有了它就不会报 找不到requirejs的错误信息了
  • phantomjs-prebuilt // phantomjs 通过 npm 安装的版本
  • sinon // 测试辅助工具,提供 spy、stub、mock 三种测试手段,模拟特定场景
  • sinon-chai

webpack 相关

  • webpack
  • babel-loader
  • css-loader
  • istanbul-instrumenter-loader // 代码覆盖率统计工具
  • karma-sourcemap-loader
  • style-loader
  • url-loader
  • vue-loader
  • vue-style-loader
  • extract-text-webpack-plugin

vue 核心包

  • vue
  • vue-template-compiler
  • vue-router

2、如何配置

上面那么一大坨包安装好了,接下来该配置。配置主要是两个,一是 karma 的配置文件,另一个是 karma 需要的webpack 配置文件。webpack 的配置文件是为了解析那些需要测试的源文件的,说白了就是 vue 相关的文件,然后再给karma 的单元测试用例去识别。

webpack3 配置文件
我是手动创建一个webpack.test.config.js 文件,然后内容配置如下

webpack 相关知识可以参考我之前写的一篇

var path = require("path")
var webpack = require("webpack")
var ExtractTextPlugin = require(''extract-text-webpack-plugin'')

function resolve(dir) {

    return path.join(__dirname, ''..'', dir)
}

var webpackConfig = {

    module: {

        rules: [

            // babel-loader
            {
                test: /\.js$/,
                use: ''babel-loader'',
                include: [resolve(''src''), resolve(''test'')]
            },

            // 为了统计代码覆盖率,对 js 文件加入 istanbul-instrumenter-loader
            {
                test: /\.(js)$/,
                exclude: /node_modules/,
                include: /src|packages/,
                enforce: ''post'',
                use: [{
                    loader: "istanbul-instrumenter-loader",
                    options: {
                        esModules: true
                    },
                }]
            },

            // vue loader
            {
                test: /\.vue$/,
                use: [{
                    loader: ''vue-loader'',
                    options: {
                        // 为了统计代码覆盖率,对 vue 文件加入 istanbul-instrumenter-loader
                        preLoaders: {
                            js: ''istanbul-instrumenter-loader?esModules=true''
                        }
                    }
                }]
            },

            // css loader
            {
                test: /\.css$/,
                use: ExtractTextPlugin.extract({
                    use: ''css-loader'',
                    fallback: ''vue-style-loader''
                })
            },

            // img loader
            {
                test: /\.(png|gif|jpe?g)(\?\S*)?$/,
                use: [{loader: ''url-loader''}]
            },

            // font loader
            {
                test: /\.(eot|woff|woff2|ttf|svg)(\?\S*)?$/,
                use: [{loader: ''url-loader''}]
            },
        ]
    },

    resolve: {
        extensions: [''.js'', ''.vue'', ''.json''],
        alias: {
            ''vue$'': ''vue/dist/vue.esm.js'',
            ''@'': resolve(''src''), // 调用组件的时候方便点
        }
    },

    plugins: [
        new webpack.DefinePlugin({
            ''process.env'': {
                NODE_ENV: ''"production"''
            }
        })
    ]
}

module.exports = webpackConfig

karma配置文件

直接 cd 到你的项目,然后执行下面命令,会提示你是否使用 require.js、浏览器环境、测试脚本存放位置等等。

$ karma init

之后就会生成一个karma.config.js 文件,配置形式我是直接仿照vue-cli 官方的例子:

var webpackConfig = require(''../../build/webpack.test.config'');

module.exports = function (config) {
    config.set({
        // to run in additional browsers:
        // 1. install corresponding karma launcher
        //    http://karma-runner.github.io/0.13/config/browsers.html
        // 2. add it to the `browsers` array below.
        browsers: [''PhantomJS''],
        frameworks: [''mocha'', ''sinon-chai'', ''phantomjs-shim''],
        reporters: [''spec'', ''coverage''],
        files: [''index.js''],
        preprocessors: {
            ''./index.js'': [''webpack'', ''sourcemap'']
        },

        webpackMiddleware: {
            noInfo: true
        },
        // 不显示 `webpack` 打包日志信息
        webpackServer: {
            noInfo: true
        },
        webpack: webpackConfig,
        coverageReporter: {
            dir: ''./coverage'',
            reporters: [
                { type: ''lcov'', subdir: ''.'' },
                { type: ''text-summary'' }
            ]
        }
    })
}

3、搭建目录结构

├─build 
│      webpack.test.config.js
│
├─src 
│
├─package.json
│
└─test 
      └─unit
          │  index.js
          │  karma.config.js
          │
          ├─coverage
          │
          └─specs
               *.spec.js

测试文件相关都放置在 test/unit 下,入口文件为 index.js,每个vue 组件对应的测试用例名为组件名称.spec.js,根据 istanbul-instrumenter-loader 文档的说明,测试总入口文件 index.js 内容如下:

import Vue from ''vue''

Vue.config.productionTip = false

// 测试所有以 .spec.js 名称结尾的文件
// require all test files (files that ends with .spec.js)
const testsContext = require.context(''./specs'', true, /\.spec$/)
testsContext.keys().forEach(testsContext)

// 要求除main.js之外的所有src文件进行覆盖
// require all src files except main.js for coverage.
// you can also change this to match only the subset of files that
// you want coverage for.
const srcContext = require.context(''../../src'', true, /^\.\/(?!main(\.js)?$)/)
srcContext.keys().forEach(srcContext)

4、简单的 vue 组件单元测试

我们在 src 目录下创建一个 Hello.vue 组件


<template>
   <div>msg</div>
</template>
<script>
export default {
  name: ''hello'',
  data () {
    return {
      msg: ''Welcome to Your Vue.js App''
    }
  }
}
</script>

然后在 test/unit/specs 下创建一个 Hello.spec.js 文件,再写个简单的单元测试用例:

import Vue from ''vue''
import Hello from ''@/components/Hello''

describe(''Hello.vue'', () => {
  it(''should render correct contents'', () => {
    const Constructor = Vue.extend(Hello)
    const vm = new Constructor().$mount()
    expect(vm.$el.querySelector(''.hello h1'').textContent)
      .to.equal(''Welcome to Your Vue.js App'')
  })
})

5、测试输出

在 package.json 中配置命令:

 // package.json
 "scripts": {
    "test": "karma start test/unit/karma.config.js --single-run"
  }

输出结果:
2

同时在 test/unit/coverage 生成测试报告。以上就是一个简单的 vue 单元测试实例。最后奉上源代码

首发于我的个人博客

今天关于由于Webpack中的CSS,Mocha测试失败由于web服务器上的isapi和cgi限制的讲解已经结束,谢谢您的阅读,如果想了解更多关于#单元测试#以karma+mocha+chai 为测试框架的Vue webpack项目(二)、05webpack中html-webpack-plugin的2个作用、css – 在webpack中使用本地Web字体、karma+mocha+webpack3 搭建 vue2 单元测试环境的相关知识,请在本站搜索。

本文标签: