Tuesday, October 24, 2017

Introduce Jasmine/Karma tests to an Angular 4 application which doesn't have tests.

I fought through this today. In attempting to run a TypeScript file with some tests in it with...

npm test

 
 

...I hit this error:

'Error: no test specified'

 
 

I got around that by putting the following the "scripts" section of package.json which breaks down along name, version, description, scripts, dependencies, napa, devDependencies, overrides, and engines properties:

"test": "jasmine",

 
 

Then, I hit this error:

'jasmine' is not recognized as an internal or external command

 
 

I added the following to the "dependencies" section of package.json:

  1. "jasmine": "2.8.0",
  2. "karma-cli": "1.0.1",
  3. "karma-jasmine-spec-runner-reporter": "0.1.5",

 
 

I ran...

npm install

 
 

...to loop in the three dependencies I just put in package.json. Then I hit this error:

No specs found

 
 

In the short term I changed...

"test": "jasmine",

 
 

...to first...

"test": "jasmine init",

 
 

...and then...

"test": "jasmine examples",

 
 

...before switching it back and after each change I ran...

npm test

 
 

...and that created a "spec" folder parallel to the "node_modules" folder which was also parallel to a "src" folder where the guts of the app were kept. Now when I ran tests it successfully ran some dummy tests which were put into that directory, the "spec" folder. Well, that is not where we want to run tests, is it? There is a jasmine.json file at spec\support\jasmine.json which had a line of notation like so in it:

"spec_dir": "spec",

 
 

I changed this to be:

"spec_dir": "src",

 
 

...and was soon back to:

No specs found

 
 

Back at spec\support\jasmine.json again, I addressed this by setting this line of configuration:

"**/*[sS]pec.js"

 
 

...to...

"**/*[sS]pec.ts"

 
 

.ts instead of .js, get it? Alright, I was now able to run the tests in the TypeScript file I had only to get this error:

SyntaxError: Unexpected token import

 
 

Alright, Jasmine cannot handle an import statement which is of ES6 so we are not going to be able to run tests against TypeScript tests directly. Instead the TypeScript tests need to compile to JavaScript tests and that means that the things they test need to be compiled to JavaScript too or else the dependencies will be jacked up. OK! I set the .ts back to .js, undoing the most recent change I give above, and then I set out to compile TypeScript. One may go to: View > Tool Windows > TypeScript YOURVERSIONHERE ...in WebStorm which will bring up a pane that has a "Compile All" icon/button to click on.

No comments:

Post a Comment