0

Before starting, this is not a duppe of ReferenceError can't find variable: $

I'm writting tests in TypeScript with Karma. My code makes use of $ for a simple fact, that the application we run our App uses jQuery, but we don't, so instead of installing jQuery we only declare the variable in a globals.ts file:

declare var $: any

The code works just fine, no problems. But the tests fail:

ReferenceError: Can't find variable: $

in my Karma.conf.js I already make reference of all ts files, this includes the global.ts with the global variabel $:

// list of files / patterns to load in the browser
files: [
  'init-test-bed.spec.ts',
  'src/**/*.ts',
  // 'src/**/*.html',
  { pattern: 'node_modules/babel-polyfill/browser.js', instrument: false }
],

but it doens't work.

Is this a problem with es6? Or what am I missing? Why does my code work and my test doesn't? This is for sure something with karma configuration, but I cannot find out what.

EDIT:

I found a workaround, I don't think that is the solution because I don't want to reference jQuery, all I want is to have a global scoped variable:

// list of files / patterns to load in the browser
files: [
  'init-test-bed.spec.ts',
  'src/**/*.ts',
  // 'src/**/*.html',
  { pattern: 'node_modules/babel-polyfill/browser.js', instrument: false },
  'https://code.jquery.com/jquery-1.11.2.min.js'
],

where I referenced jQuery, I should be able to declare my global.ts wchich contains my global variable $, but karma doesn't seem to like it.

DAG
  • 2,460
  • 5
  • 33
  • 61

1 Answers1

0

When you declare something exists:

declare var $: any

You are telling the compiler that "something it doesn't know about will be available at runtime".

Whenever you use an ambient declaration, you also need to think about how that declaration will be satisfied. In your case, it can be satisfied by including jQuery at runtime.

jQuery must load before the file that depends on it. The order of patterns determines the order in which files are included in the browser...

files: [
  'https://code.jquery.com/jquery-1.11.2.min.js'
  'init-test-bed.spec.ts',
  'src/**/*.ts',
  // 'src/**/*.html',
  { pattern: 'node_modules/babel-polyfill/browser.js', instrument: false }
],
Fenton
  • 241,084
  • 71
  • 387
  • 401
  • It makes sense except that in `karma.conf.js` I declared the variable so karma knows about it. that is not the case. – DAG Dec 12 '17 at 10:53
  • It needs to be loaded in the correct order - updated config attached to answer. – Fenton Dec 12 '17 at 12:49
  • it works in the order shown in my post. I don't want to load jQuery. I want to avoid it and it does't make any sense – DAG Dec 12 '17 at 12:57
  • What line of code depends on `$`? Instead of `declare`-ing `$` you could probably write a very simple test double for it. – Fenton Dec 12 '17 at 13:35