I cannot run jasmine tests in Karma if my app code uses ng2-boostrap module, which depends on moment.js library.
The app works fine in the browser, and the jasmine tests can be run in the browser by adding mapping for moment to System:
-- unit-test.html ---
...
<script src="node_modules/ng2-bootstrap/bundles/ng2-bootstrap.min.js"></script>
...
<body>
<script>
// #2. Configure SystemJS to use the .js extension
// for imports from the app folder
System.config({
packages: {
'app': {defaultExtension: 'js'}
},
map: {
'moment': 'node_modules/moment/moment.js'
}
});
I tried to the same inside karma.shim but it doesn't work. I am getting:
Error: XHR error (404 Not Found) loading http://localhost:9876/node_modules/moment/moment.js
Error loading http://localhost:9876/node_modules/moment/moment.js as "moment" from http://localhost:9876/ng2-bootstrap/components/datepicker/date-formatter
at addToError (D:/Projects/Angular/karma-ngbootstrap/node_modules/systemjs/dist/system.src.js:41:18)
In my karma.conf I have
files: [
...
{pattern: 'node_modules/angular2/bundles/testing.dev.js', included: true, watched: true},
....
{pattern: 'node_modules/moment/moment.js',included: true, watched: true},
{pattern: 'node_modules/ng2-bootstrap/bundles/ng2-bootstrap.min.js', included: true, watched: true},
{pattern: 'karma-test-shim.js', included: true, watched: true},
{pattern: 'app/**/*.js', included: false, watched: true},
....
And in the karma-test-shim:
System.config({
packages: {
'base/app': {
defaultExtension: false,
format: 'register',
map: Object.keys(window.__karma__.files).
filter(onlyAppFiles).
reduce(function createPathRecords(pathsMapping, appPath) {
// creates local module name mapping to global path with karma's fingerprint in path, e.g.:
// './hero.service': '/base/src/app/hero.service.js?f4523daf879cfb7310ef6242682ccf10b2041b3e'
var moduleName = appPath.replace(/^\/base\/app\//, './').replace(/\.js$/, '');
pathsMapping[moduleName] = appPath + '?' + window.__karma__.files[appPath]
return pathsMapping;
}, {})
}
},
map: {
'moment': 'node_modules/moment/moment.js'
}
});
The mapping part kind of works, cause depending what I put there under moment I am getting it later in the XHR error path.
The full files can be found in the simple test project at: https://github.com/tzielins/angular-start-project
The karma configuration is based on the http://twofuckingdevelopers.com/2016/01/testing-angular-2-with-karma-and-jasmine/
I am happy to use a simpler configuration but I luck experience with System.js/Karma to start from scratch, and this one works without ng2-boostrap dependency (the code under test only imports form ng2-boostrap which is enough to trip karma, it can be commented out to have test pass).
I must be missing something obvious from System.js configuration.