jasmine tests in karma: Uncaught ReferenceError: require is not defined
Asked Answered
Q

7

50

Karma can not recognize 'require' statement in JSFileSpec.js file. Running karma.conf.js:

(function() {
    describe("DummyEmitter creation", function(){
        return it("creation", function(){
            var DummyEmitter = require('Util.DummyEmitter');
            var dummy = new DummyEmitter('someName');
            return expect(dummy).toBeDefined();
        });
    });
})();

ReferenceError: require is not defined

Quadrivalent answered 1/10, 2013 at 13:10 Comment(3)
I landed here looking for a gulp solution, adding frameworks: ['jasmine', 'requirejs'] to karma.conf.js seems to solve itOrigami
be sure to install: karma-requirejs and requirejs when using such frameworks setupMarlanamarlane
https://mcmap.net/q/355723/-karma-jasmine-failure-quot-referenceerror-is-not-defined-quot-in-angular-11/7186739Lona
D
51

I was facing same issue, when trying to use require('module_name') (CommonJS style modules) inside a test case and running it using Karma.

The reason was require function is not available to browser (it is undefined). To provide it to browser we can browserify the test js files before Karma runs test case in browser using karma-browserify.

Install karma-browserify using npm install karma-browserify --save-dev

Update karma.conf.js

 frameworks: ['jasmine', 'browserify'],
 preprocessors: {
    'app/tests/*.js': [ 'browserify' ]
 },
 plugins: [..., 'karma-browserify'],

After these changes browserified file is run in browser by Karma, in which require is defined, and test case runs successfully

Dutiful answered 11/6, 2015 at 13:6 Comment(8)
I get this error even afte radding karma-browserify to the plugins array: Error: No provider for "framework:browserify"! (Resolving: framework:browserify)Requiem
Karma-Browserfy needs browserfy installed. You'll need browserfy first of all, so running "npm install --save-dev karma-browserify browserify watchify" will fix the no provider problem. Make sure to follow the preprocessors: with a comma so you don't break your karma.conf.js file. Watchify is needed to watch for changes of the files that are being included.Gorges
tried all suggestions in this post and the witchify command, they all finish with no errors, but can't get rid of the require-is-not-defined errorJaffe
remember to also add plugins: [ 'karma-browserify', ... ] otherwise, it will complain "Can not load "browserify"" and you will spend the next few hours frustrating.Expertise
remember use following imports in all of your tests- import 'reflect-metadata' require('zone.js/dist/zone');Zymogenic
@GreatQuestion my saviorKaycekaycee
Actually, with these versions placed on package.json you don't need to add "plugins" field. :D "karma": "^1.7.0", "karma-browserify": "^5.1.1", "karma-chrome-launcher": "^2.2.0", "karma-phantomjs-launcher": "^1.0.4", "karma-jasmine": "^1.1.0",Labiate
I was seeing a Error: No provider for "framework:jasmine"! error when attempting to run karma until I followed @Bruno Casali's advice and removed the "plugins" field from karma.conf.js.Monosaccharide
S
23

You might be using a glob pattern that is picking up stuff inside karma's bin directory. Try to execute your tests by using absolute paths to see if that fixes it.

If so then you know your glob pattern is grabbing stuff you did not want to.

For example change

{pattern: '**/**/*_test.js'},

to

{pattern: 'stuff/dashboard/home-page_test.js'},

see if that fixes your problem.

Socialism answered 11/11, 2014 at 19:27 Comment(1)
Fixed it for me, it was trying grab everything from my node_modules folderMarque
B
5

Karma is a test runner that runs your tests in a browser. Whatever browser you setup doesn't know what the require function is.

To use jasmine with node try jasmine-node. https://github.com/mhevery/jasmine-node

To have karma run jasmine node tests, try (wait for it....) jasmine-node-karma. https://npmjs.org/package/jasmine-node-karma

Here's the jasmine wiki pages where I found the above info. https://github.com/pivotal/jasmine/wiki

Hope this helps.

Boadicea answered 12/11, 2013 at 3:16 Comment(2)
yeah this does not help. i've configured path to require.js in karma.conf.js and it still errors on "require is not defined"Houk
requirejs is not the same as the node require function. It look like you can set up requirejs to work on both server and client (browser) but it'll take more setup then just adding it to the path.Boadicea
M
3

I've encountered today a similar issue. In my case the solution was quite simple. I am using Babel via Webpack to process .jsx files. Files with the .jsx extension did test successfully, while simple .js files throwed a reference error.

If anyone has a similar or equivalent setup they might be able to share the same solution.

In karma.config.js I had to specify preprocessors for .js files as I did for the .jsx ones. Here's an example:

preprocessors: {
  "app/tests/**/*.test.jsx": ["webpack", "sourcemap"],
  "app/tests/**/*.test.js": ["webpack", "sourcemap"]
},

I better add that in my case Webpack passes the code to Babel to compile so that it can run in the browser. I can copy and paste the entire webpack.config.js and karma.config.js if anyone needs them.

Medrano answered 25/12, 2016 at 17:42 Comment(0)
P
0

I use webpack for that purpose. I published my configuration on npm to save my time for the future projects. Just run npm install webpack-karma-jasmine, and create config files for webpack and karma as described in docs: https://www.npmjs.com/package/webpack-karma-jasmine

Peacoat answered 31/7, 2017 at 18:8 Comment(0)
A
0

If someone still couldnt resolve with the above solutions, this is what helped me. yarn add browserify and watchify

Auten answered 9/8, 2017 at 21:14 Comment(0)
T
-1
  module.exports = function(config) {
    config.set({

      basePath: '',


      frameworks: ['mocha', 'chai'],

      files: [
        'test/*.test.js'
      ],

      exclude: [
      ],

      preprocessors: {
        'test/*.test.js': ['webpack']
      },

      webpack: {
        mode: "none",
        module: {
          rules: [
            { test: /\.js?$/, loader: "babel-loader",  options: { presets: ["env"] }, }
          ]
        }
      },

      reporters: ['progress'],

      port: 9876,

      colors: true,

      logLevel: config.LOG_INFO,

      autoWatch: true,

      browsers: ['Chrome'],

      singleRun: false,

      concurrency: Infinity,

      browserNoActivityTimeout: 100000
    })
  }

use webpack

Tune answered 12/8, 2018 at 13:57 Comment(1)
Welcome to StackOverflow. Could you please add some more information how this solves the problem.Petey

© 2022 - 2024 — McMap. All rights reserved.