2

I'm writing a Node.js project using TypeScript. The compilation is done using tsc, I am not using any task runner like Gulp or Grunt. I'll try to be as concise as possible, however if any further details are needed I'll gladly provide them.

I have the following class:

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

When I try to test it using Jasmine with Karma and PhantomJS, I get the following error: Error: Could not find module 'events' from '(...)/foo.js'. For me it seems that PhantomJS doesn't know where to take events module from.

My karma.conf.js looks as follows:

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
  })
}

How can I let PhantomJS know, that the events module comes from Node.js inner modules?

1 Answers1

1

Well, according to an answer to a similar question on SO it's not possible to do so on purpose.

Karma is a test runner for testing frontend code only. That's how it was designed. Therefore, you cannot require any node internal library without using weird workarounds.

If you'd like to test the backend code, go ahead and use e.g. Mocha and Chai instead of Karma and Jasmine. Moving to this libraries wasn't very painful and I can totally recommend doing so.

Moreover, this article provides good introduction on how to use Mocha with TypeScript so I suggest reading it first.

Community
  • 1
  • 1