Laravel + VueJs + Webpack + Karma =痛苦的世界

时间:2017-03-15 20:24:32

标签: laravel vue.js karma-jasmine

如果您使用Laravel的Elixir进行webpack配置,是否可以为VueJs编写单元测试?

VueJs 2x有一个非常简单的组件测试示例:Vue Guide Unit testing

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

然后......

// Import Vue and the component being tested
import Vue from 'vue'
import MyComponent from 'path/to/MyComponent.vue'

describe('MyComponent', () => {
  it('has a created hook', () => {
    expect(typeof MyComponent.created).toBe('function')
  })
  it ...etc
})

并在此处提供了一个业力配置文件示例:https://github.com/vuejs-templates

但是Karma配置文件需要webpack配置文件

webpack: webpackConfig,

唯一的问题是Laravel的Elixir正在创建webpack配置,因此无法包含它。

我尝试根据https://github.com/vuejs-templates/webpack中的示例创建另一个webpack配置文件。

这样的事情:

var path = require('path');
var webpack = require('webpack');

module.exports = {
    entry: './src/main.js',
    output: {
        path: path.resolve(__dirname, './dist'),
        publicPath: '/dist/',
        filename: 'build.js'
    },
    module: {
        rules: [
            {
                test: /\.vue$/,
                loader: 'vue-loader',
                options: {
                    loaders: {
                        // Since sass-loader (weirdly) has SCSS as its default parse mode, we map
                        // the "scss" and "sass" values for the lang attribute to the right configs here.
                        // other preprocessors should work out of the box, no loader config like this necessary.
                        'scss': 'vue-style-loader!css-loader!sass-loader',
                        'sass': 'vue-style-loader!css-loader!sass-loader?indentedSyntax'
                    }
                    // other vue-loader options go here
                }
            },
            {
                test: /\.js$/,
                loader: 'babel-loader',
                exclude: /node_modules/
            },
            {
                test: /\.(png|jpg|gif|svg)$/,
                loader: 'file-loader',
                options: {
                    name: '[name].[ext]?[hash]'
                }
            }
        ]
    },
    resolve: {
        alias: {
            'vue$': 'vue/dist/vue.esm.js'
        }
    },
    devServer: {
        historyApiFallback: true,
        noInfo: true
    },
    performance: {
        hints: false
    },
    devtool: '#eval-source-map'
}

并将其包括在内......

// Karma configuration
// Generated on Wed Mar 15 2017 09:47:48 GMT-0500 (CDT)
var webpackConf = require('./karma.webpack.config.js');
delete webpackConf.entry;

module.exports = function(config) {
  config.set({

    webpack: webpackConf, // Pass your webpack.config.js file's content

    webpackMiddleware: {
      noInfo: true,
      stats: 'errors-only'
    },

但我收到的错误似乎表明webpack没有做任何事情。

ERROR in ./resources/assets/js/components/test.vue
Module parse failed: /var/www/test/resources/assets/js/components/test.vue Unexpected token (1:0)
You may need an appropriate loader to handle this file type.
| <template>
|     <span >{{test}}</span>
| </template>

2 个答案:

答案 0 :(得分:2)

好的,我让这个工作了。一些可能有帮助的事情。

我最初运行gulp,并试图在我的流浪盒中运行测试,以尝试匹配服务器配置。我认为这使得在互联网上找到示例和答案变得更加困难。

好的,我遇到的主要问题是webpack没有处理我的测试文件中包含的组件。我将webpack配置从laravel-elixir-vue-2 / index.js节点模块直接复制到Karma配置文件中,然后开始工作。

关键是karma-webpack插件需要解析和模块加载器配置设置(使用别名和扩展解析)才能工作。

希望这有助于某人。

karma.conf.js:

dota2.exe

答案 1 :(得分:0)

我遇到了完全相同的问题。接受的答案对我来说并不完全有用。以下解决了我的问题:

  1. 为webpack安装相关的加载器:

    npm install --save-dev vue-loader file-loader url-loader

  2. 创建webpack配置文件(注意格式)。接受的答案引用了错误,引用了webpack.config.js文件的无效格式。至少和我在一起。

  3. <强> webpack.config.js

    module.exports = {
      module: {
        rules: [
          {
            test: /\.vue$/,
            use: [
              { loader: 'vue-loader' }
            ]
          },
          {
            test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
            use: [
              { 
                loader: 'file-loader',
                query: {
                  limit: 10000,
                  name: '../img/[name].[hash:7].[ext]'
                }
              }
            ]
          },
          {
            test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
            use: [
              {
                loader: 'url-loader',
                query: {
                  limit: 10000,
                  name: '../fonts/[name].[hash:7].[ext]'
                }
              }
            ]
          }
        ]
      }
    }
    

    <强> karma.conf.js

    // Karma configuration
    
    var webpackConf = require('./webpack.config.js');
    delete webpackConf.entry
    
    module.exports = function(config) {
        config.set({
    
            frameworks: ['jasmine'],
    
            port: 9876, // web server port
    
            colors: true,
    
            logLevel: config.LOG_INFO,
    
            reporters: ['progress'], // dots, progress
    
            autoWatch: true, // enable / disable watching files & then run tests
    
            browsers: ['Chrome'], //'PhantomJS', 'Firefox',
    
            singleRun: true, // if true, Karma captures browsers, runs the tests and exits
    
            concurrency: Infinity, // how many browser should be started simultaneous
    
            webpack: webpackConf, // Pass your webpack.config.js file's content
    
            webpackMiddleware: {
                noInfo: true,
                stats: 'errors-only'
            },
    
            /**
             * base path that will be used to resolve all patterns (eg. files, exclude)
             * This should be your JS Folder where all source javascript
             * files are located.
             */
            basePath: './resources/assets/js/',
    
            /**
             * list of files / patterns to load in the browser
             * The pattern just says load all files within a
             * tests directory including subdirectories
             **/
            files: [
                {pattern: 'tests/*.js', watched: false},
                {pattern: 'tests/**/*.js', watched: false}
            ],
    
            // list of files to exclude
            exclude: [
            ],
    
           /**
            * pre-process matching files before serving them to the browser
            * Add your App entry point as well as your Tests files which should be
            * stored under the tests directory in your basePath also this expects
            * you to save your tests with a .spec.js file extension. This assumes we
            * are writing in ES6 and would run our file through babel before webpack.
            */
            preprocessors: {
                'app.js': ['webpack', 'babel'],
                'tests/**/*.spec.js': ['babel', 'webpack']
            },
        })
    }
    

    然后运行karma start,一切都应该有效。