Hi lovely people my-gs500-blog-readers! I'm so glad to meet you again!
Today i want to speak about unit tests. Yes, a already wrote some series about unit testing angular1 directives, but now it is slightly different.
Why? Because i'm talking about angular typescript project.
Remember this angular-seed repo, we learned how to translate it to typescript(in this post)?
So, since the project is now contains only typescript (.ts) files - current tests would not work anymore (Because all the code that tests should be testing is not exists yet, it need to be transpilled to javascript)
Translate The Tests To Typescript
First thing to start with - lets translate all the tests to typescript: This is very simple, instead of:
'use strict';
describe('myApp.version module', function() {
beforeEach(module('myApp.version'));
describe('version service', function() {
it('should return current version', inject(function(version) {
expect(version).toEqual('0.1');
}));
});
});
now it is:
import * as angular from "angular";
import "angular-mocks";
import "phantomjs-polyfill";
import {version} from './version'
describe('myApp.version module', () => {
beforeEach(angular.mock.module('myApp.version'));
describe('version service', () => {
it('should return current version', () => {
expect(version).toEqual('0.1');
});
});
});
Not a big difference, right?
Karma Is A Bitch
Next things we need to change karma.conf file, to explain to karma: "you should load ts files now, baby"
...
files: [
'./node_modules/phantomjs-polyfill/bind-polyfill.js',
'./app/test.ts'
]
...
Processing With Webpack
For convert ts files to ES5 you need to use some transpiling tool, for example webpack:
...
plugins: [
require('karma-webpack'),
require('karma-sourcemap-loader'),
require('karma-jasmine'),
require('karma-phantomjs-launcher'),
require('karma-chrome-launcher')
],
webpack: webpackConfig,
webpackMiddleware: {
stats: { chunks: false },
},
...
For full code look in this repo