Karma tests, PhantomJS error: Could not find module 'events'

Karma tests, PhantomJS error: Could not find module 'events'

我正在使用 TypeScript 编写一个 Node.js 项目。编译是使用 tsc 完成的,我没有使用任何任务运行程序,如 Gulp 或 Grunt。我会尽量简明扼要,但如果需要更多详细信息,我会很乐意提供。

我有以下 class:

// Foo.ts
import { EventEmitter } from 'events';
export class Foo extends EventEmitter {
  //...
}

当我尝试使用 Jasmine 与 Karma 和 PhantomJS 对其进行测试时,出现以下错误:Error: Could not find module 'events' from '(...)/foo.js'。对我来说,PhantomJS 似乎不知道从哪里获取 events 模块。

我的 karma.conf.js 看起来如下:

var createCoverageReport = false;

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

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',
    frameworks: ['jasmine', 'karma-typescript', 'es6-shim'],
    files: [
      'src/**/*.ts'
    ],
    exclude: [
    ],
    preprocessors: {
      'src/**/*.ts': ['karma-typescript']
    },
    reporters: ['spec'].concat(createCoverageReport ? ['karma-typescript'] : []),
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['PhantomJS'],
    singleRun: false,
    concurrency: Infinity
  })
}

如何让 PhantomJS 知道 events 模块来自 Node.js 个内部模块?

好吧,根据 an answer to a similar question on SO 故意这样做是不可能的。

Karma 是用于测试前端代码的测试运行器。这就是它的设计方式。因此,如果不使用奇怪的解决方法,就不能要求任何节点内部库。

如果您想测试后端代码,请继续使用例如Mocha and Chai 而不是 Karma 和 Jasmine。迁移到这个库并不是很痛苦,我完全可以推荐这样做。

此外,this article 很好地介绍了如何将 Mocha 与 TypeScript 结合使用,因此我建议先阅读它。