ko_yyw
Last Updated: February 25, 2016
·
1.494K
· wendy0402

setup javascript test environment using karma,mocha, chai, and requirejs

Recently I create a project built upon javascript. Setting up test environment was quite hard for me at the first time. It takes quite long time and I found several errors. So here I want to share my problems, and the solution:

I. Different RequireJS BaseURL

problem: Requirejs baseUrl for test-environment and your application is different. It cause several dependecies problem

example:

main.js

require.config({
  baseUrl: './app/js', // folder app/js
  paths: {
   jquery: 'js/lib/jquery/jquery',
   backbone: 'js/lib/backbone/backbone',
   underscore: 'js/lib/underscore/underscore',
   text: 'js/lib/text/text'
  }
 });

test-main.js

require.config({
  // Karma serves files under /base, which is the basePath from your config file
  baseUrl: '/base/app/', //folder app
  paths: {
    'jquery': 'js/lib/jquery/jquery',
    'underscore': 'js/lib/underscore/underscore',
    'backbone': 'js/lib/backbone/backbone',
    'text': 'js/lib/text/text'
  },

solution: always make both test-main.js and main.js baseUrl

test-main.js

baseUrl: '/base/app/js'

main.js

baseUrl: './app/js'

II. chai and requirejs problem

problem: Uncaught TypeError: Cannot read property 'should' of undefined

solution: put requirejs before chai in karma framework list( ref: https://github.com/xdissent/karma-chai/issues/5)

III. No timeStamp for file

problem: ERROR: 'There is no timestamp for /base/app/templates/setting.js!'

solution: try to check your files list in karma.conf.js. It is because the file is not included

last but not least, here is my configuration for karma.conf.js and test-main.js.
Hope it helps you!