【问题标题】:karma setup giving require is not defined业力设置给予要求未定义
【发布时间】:2017-07-31 06:16:52
【问题描述】:

我是在这里设置业力和测试的新手,所以我已经通过一堆示例来设置我的环境。 但是,每当我运行 karma start 时,它都会给我这个:

Uncaught ReferenceError: require is not defined
at test/person-test.js:1

我想我可能没有正确设置我的karma.conf.js,有人知道吗?这就是我所拥有的:

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

    basePath: '',
    frameworks: ['jasmine', 'browserify'],
    files: [
      'test/**/*.js'
    ],
    exclude: [],
    preprocessors: {
      'src/**/*.js': ['browserify']
    },
    plugins: [
      'karma-chrome-launcher',
      'karma-jasmine',
      'karma-browserify'
      ],
    browserify: {
      debug: true,
      transform: [ 'brfs', 'browserify-shim' ]
    },
    reporters: ['progress'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false,
    concurrency: Infinity
  })
}

我有这样的文件结构:

.
├── src
|   └── person.js
├── test
|   ├── person-test.js
├── karma.conf.js
└── package.json

我的person.js 文件是这样的:

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  upperCaseName() {
    this.name = this.name.upperCaseName();
  }
}

module.exports = Person;

并且(到目前为止)我的person-test.js 是:

const Person = require('../src/person.js')

【问题讨论】:

    标签: javascript testing karma-runner


    【解决方案1】:

    基本上,您需要为浏览器转换源代码,将 require 调用替换为实际的模块代码。看看这些实用程序:

    http://browserify.org/ - 它完全符合您的要求

    https://webpack.github.io/ - 一个更复杂的 Web 打包框架,具有许多其他有用的功能。

    更新:

    Karma 是一个测试运行器,可在浏览器中运行您的测试。无论你设置什么浏览器都不知道 require 函数是什么。

    要在节点上使用 jasmine,请尝试 jasmine-node。 https://github.com/mhevery/jasmine-node

    【讨论】:

    • 什么意思?如果这只是一个小型非浏览器应用程序怎么办? bundle.js 的脚本标签应该放在哪里?
    • 浏览器不理解require语句,需要将源代码编译成浏览器可以理解的
    • 我尝试运行 browserify src/person.js > bundle.js 并创建 index.html 并放入 <script src="bundle.js"></script>。我还需要做什么才能让我的karma start 工作吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-07
    • 2017-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-06
    • 1970-01-01
    相关资源
    最近更新 更多