Using SystemJS with Karma - 404 on package.json - angularjs

Problem:
Attempting to integrate SystemJS config with Karma using karma-systemjs, however Karma is complaining about not being able to find the package.json file for each import:
...
10 07 2017 13:38:15.107:WARN [web-server]: 404: /node_modules/angular-mocks/package.json
10 07 2017 13:38:15.380:WARN [web-server]: 404: /node_modules/moment/package.json
10 07 2017 13:38:15.382:WARN [web-server]: 404: /node_modules/angular/package.json
PhantomJS 2.1.1 (Windows 7 0.0.0) ERROR
Error: (SystemJS) XHR error (404 Not Found) loading http://localhost:9876/node_modules/angular-mocks/package.json
Error loading http://localhost:9876/node_modules/angular-mocks/package.json
Error loading build/js/app.spec.js
PhantomJS 2.1.1 (Windows 7 0.0.0): Executed 0 of 0 ERROR (0.945 secs / 0 secs)
Above has been truncated, but there are several more missing package.json warnings above the output. Also these errors only relate to Karma, actually application itself runs fine with below setup.
Dependency Versions:
"karma": "1.7.0"
"karma-jasmine": "1.1.0"
"karma-systemjs": "0.16.0"
"systemjs": "0.19.47"
SystemJS Config:
(Referenced from: https://github.com/systemjs/systemjs/issues/767#issuecomment-139515090)
System.config({
defaultJSExtensions: true,
transpiler: "babel",
babelOptions: {
"optional": [
"runtime",
"optimisation.modules.system"
]
},
paths: {
'*': './node_modules/*',
},
packageConfigPaths: ['./node_modules/*/package.json'],
map: {
'systemjs': './node_modules/systemjs/dist/system.js',
'system-polyfills': './node_modules/systemjs/dist/system-polyfills.js',
'babel': './node_modules/babel-core/browser.js',
'angular-feature-flags': './node_modules/angular-feature-flags/dist/featureFlags.min.js',
crypto: '#empty',
fs: '#empty',
stream: '#empty'
}
});
Karma Config:
module.exports = function (config) {
"use strict";
config.set({
autoWatch: true,
singleRun: false,
port: 9876,
frameworks: ["systemjs", "jasmine"],
babelPreprocessor: {
options: {
compact: true
}
},
files: [
"node_modules/phantomjs-polyfill-object-assign/object-assign-polyfill.js",
{pattern: "app/assets/images/**/*", watched: false, included: false, served: true},
"build/**/*spec*.js"
],
systemjs: {
configFile: "./config.js",
serveFiles: [
'./build/**/*.js'
]
},
browsers: ["PhantomJS"],
reporters: ["spec"]
});
};

karma-systemjs is supposed to read your SystemJS configuration and automatically tell karma to serve the files that you tell SystemJS about. However, I looked at the code of karma-systemjs and I don't see any provision there to deal with packageConfigPaths. (And the project needs a new maintainer, which does not inspire confidence.) Therefore, you should add an element to your files configuration like:
{ pattern: "node_modules/**/package.json", included: false }
I'm suggesting a pattern with ** so that you can automatically handle paths like node_modules/#angular/core/package.json, which are more than one level deep.

Related

Can't find variable angular in spec.js Using Webpack+Karma+Jasmine for AngularJS unit Testing

I am getting following error while testing angular app.
Can't find variable: angular in spec/abc.spec.js
My app is running fine with webpack. Also karma gives success on
expect(true).toBe(true);
Following is my skeleton:
abc.ts
var angular = require('angular');
var angular_mocks = require('angular-mocks');
var specs = require('../spec/abc.spec.js');
var myApp = angular.module('myApp',[]);
myApp.controller('MyController', function($scope) {
$scope.spices = [{"name":"pasilla", "spiciness":"mild"},
{"name":"jalapeno", "spiciness":"hot hot hot!"},
{"name":"habanero", "spiciness":"LAVA HOT!!"}];
$scope.spice = "habanero";
});
abc.spec.js
describe('myController function', function () {
describe('myController', function () {
var $scope;
beforeEach(angular.mock.module('myApp'));
beforeEach(inject(function ($rootScope, $controller) {
$scope = $rootScope.$new();
$controller('MyController', {$scope: $scope});
}));
it('should create "spices" model with 3 spices', function () {
expect($scope.spices.length).toBe(3);
});
it('should set the default value of spice', function () {
expect($scope.spice).toBe('habanero');
});
it('should set the default value of spice', function () {
expect(angular).toBeDefined();
});
});
});
karma.config.js
// Karma configuration
// Generated on Wed Dec 21 2016 19:28:26 GMT+0530 (India Standard Time)
var webConfig = require('./karma.conf')
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'spec/*.js'
],
// list of files to exclude
exclude: [
'src/bundle.js'
],
webpack: webConfig,
webpackMiddleware: {
stats: 'errors-only'
},
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'src/*.js': ['coverage', 'webpack']
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress','coverage'],
coverageReporter: {
type : 'html',
dir : 'coverage/'
},
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['PhantomJS'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,
// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity
})
}
webpack.config.js
var webConfig = {
entry: './src/abc',
output:{
path: 'src',
filename:'bundle.js'
},
resolve: {
root: ['src', "node_modules"],
extensions: ['', '.ts', '.js']
},
modules: {
loaders: [
{
test:/\.ts?$/,
loader:'ts-loader'
}
]
}
}
module.exports = webConfig;
tsconfig.js
{
"compilerOptions": {
"target": "es5",
"module": "amd",
"moduleResolution": "node",
"removeComments": true,
"preserveConstEnums": true,
"sourceMap": true
},
"exclude": [
"typings",
"node_modules"
]
}
ERROR:
C:\Users\namankheterpal\IdeaProjects\ngwk>karma start
webpack: bundle is now VALID.
22 12 2016 13:55:36.125:WARN [karma]: No captured browser, open http://localhost:9876/
22 12 2016 13:55:36.137:INFO [karma]: Karma v1.3.0 server started at http://localhost:9876/
22 12 2016 13:55:36.138:INFO [launcher]: Launching browser PhantomJS with unlimited concurrency
22 12 2016 13:55:36.151:INFO [launcher]: Starting browser PhantomJS
22 12 2016 13:55:37.906:INFO [PhantomJS 2.1.1 (Windows 8 0.0.0)]: Connected on socket /#GxGMuAyLHkfyOc9NAAAA with id 40162084
PhantomJS 2.1.1 (Windows 8 0.0.0) myController function myController encountered a declaration exception FAILED
ReferenceError: Can't find variable: angular in spec/abc.spec.js (line 6)
spec/abc.spec.js:6:23
spec/abc.spec.js:3:11
global code#spec/abc.spec.js:1:9
PhantomJS 2.1.1 (Windows 8 0.0.0): Executed 1 of 1 (1 FAILED) ERROR (0.006 secs / 0.001 secs)
Reffrence https://github.com/webpack/karma-webpack
Please let me know if I am missing something and if any other info is required.
Thanks in advance.
Include your angular library and your source files at
files: [
'location/angular.min.js'
'spec/*.js'
],
you have to add angular library to execute karma testing and also your source files.

Karma gives me a __karma__.start adapter error without any other error

I don't know how to fix this issue. I get no errors other than the one above. Here are my config files:
./webpack.config.js
var path = require('path');
var webpack = require('webpack');
module.exports = {
entry: './src/app/app.jsx',
output: { path: __dirname, filename: 'app.js' },
port: 9090,
devServer: {
contentBase: './src',
hot: true,
port: 9090,
publicPath: '/assets/',
noInfo: false
},
resolve: ['.js', '.jsx', ''],
module: {
loaders: [
{
test: /.jsx$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015', 'react']
}
}
]
},
};
./karma.conf.js
var webpackConfig = require('./webpack.config');
webpackConfig.devtool = 'inline-source-map';
module.exports = function(config) {
config.set({
frameworks: ['mocha', 'chai', 'sinon', 'sinon-chai'],
plugins: [
'karma-chrome-launcher',
'karma-mocha',
'karma-chai',
'karma-sinon',
'karma-sinon-chai',
'karma-sourcemap-loader',
'karma-webpack'
],
files: [
'tests.webpack.js'
],
exclude: [],
preprocessors: {
'tests.webpack.js': ['webpack', 'sourcemap']
},
webpack: webpackConfig,
webpackMiddleware: {
noInfo: true
},
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_DEBUG,
autoWatch: true,
browsers: ['Chrome'],
singleRun: true,
});
}
./tests.webpack.js
'use strict';
require('babel-polyfill');
require('core-js/fn/object/assign');
var context = require.context('./test', true, /Test\.jsx$/);
context.keys().forEach(context);
An example test file (test/app/AppTest.jsx):
'use strict';
var TestUtils = require('react-addons-test-utils');
import {expect} from 'chai';
describe('App', () => {
it('should display correct text on render', () => {
let component = TestUtils.renderIntoDocument(<App/>);
expect('hello').to.equal('hello');
});
});
Here is karma debug output (I removed the times, so it was more readable):
DEBUG: [config]: autoWatch set to false, because of singleRun
DEBUG [plugin]: Loading plugin karma-chrome-launcher.
DEBUG [plugin]: Loading plugin karma-mocha.
DEBUG [plugin]: Loading plugin karma-chai.
DEBUG [plugin]: Loading plugin karma-sinon.
DEBUG [plugin]: Loading plugin karma-sinon-chai.
DEBUG [plugin]: Loading plugin karma-sourcemap-loader.
DEBUG [plugin]: Loading plugin karma-webpack.
DEBUG [web-server]: Instantiating middleware
DEBUG [preprocessor.sourcemap]: base64-encoded source map for /Users/gasim/Stack/gasim/gasim-frontend/tests.webpack.js
INFO [karma]: Karma v1.1.0 server started at http://localhost:9876/
INFO [launcher]: Launching browser Chrome with unlimited concurrency
INFO [launcher]: Starting browser Chrome
DEBUG [temp-dir]: Creating temp dir at /var/folders/0q/z4cbhb7x49jgk2ycw4f9hxd00000gn/T/karma-37005516
DEBUG [launcher]: /Applications/Google Chrome.app/Contents/MacOS/Google Chrome --user-data-dir=/var/folders/0q/z4cbhb7x49jgk2ycw4f9hxd00000gn/T/karma-37005516 --no-default-browser-check --no-first-run --disable-default-apps --disable-popup-blocking --disable-translate --disable-background-timer-throttling http://localhost:9876/?id=37005516
DEBUG [web-server]: serving: /Users/gasim/Stack/gasim/gasim-frontend/node_modules/karma/static/client.html
DEBUG [web-server]: serving: /Users/gasim/Stack/gasim/gasim-frontend/node_modules/karma/static/karma.js
DEBUG [karma]: A browser has connected on socket /#ZLT5diBbmtOJweMIAAAA
DEBUG [web-server]: upgrade /socket.io/?EIO=3&transport=websocket&sid=ZLT5diBbmtOJweMIAAAA
DEBUG [web-server]: serving: /Users/gasim/Stack/gasim/gasim-frontend/node_modules/karma/static/favicon.ico
INFO [Chrome 51.0.2704 (Mac OS X 10.11.5)]: Connected on socket /#ZLT5diBbmtOJweMIAAAA with id 37005516
DEBUG [launcher]: Chrome (id 37005516) captured in 2.52 secs
DEBUG [middleware:karma]: custom files null null
DEBUG [middleware:karma]: Serving static request /context.html
DEBUG [web-server]: serving: /Users/gasim/Stack/gasim/gasim-frontend/node_modules/karma/static/context.html
DEBUG [web-server]: serving: /Users/gasim/Stack/gasim/gasim-frontend/node_modules/karma/static/context.js
Chrome 51.0.2704 (Mac OS X 10.11.5) ERROR
You need to include some adapter that implements __karma__.start method!
What really interests me is the following line in the debug output:
DEBUG [middleware:karma]: custom files null null
Why does it say null null? Does this mean files for tests are empty or something?
The problem here in this line here:
frameworks: ['mocha', 'chai', 'sinon', 'sinon-chai'],
There is no need to include chai or sinon. They were the ones giving me errors. So, I only kept mocha and sinon-chai and I just load chai and sinon from within my test scripts.

Error in scripting using angularjs, requirejs and karma

I'm getting a script error every time I try to load the angularjs to a test file.
When I try to put the angularjs in the requirejs define block, I get an error.
karma conf:
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', 'requirejs'],
files: [
{pattern: 'C:/workspaces/trunk/pearl/client/components/angular/angular.js', included: false},
{pattern: '../components/angular-mocks/angular-mocks.js', included: false},
{pattern: '**/*Spec.js', included: false},
'test-main.js'
],
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_DEBUG,
autoWatch: false,
browsers: ['PhantomJS'],
captureTimeout: 60000,
singleRun: true
});
};
test conf:
var tests = [];
for (var file in window.__karma__.files) {
if (window.__karma__.files.hasOwnProperty(file)) {
if (/Spec\.js$/.test(file)) {
tests.push(file);
}
}
}
requirejs.config({
paths: {
'angular': '../components/angular/angular',
'angular-mocks': '../components/angular-mocks/angular-mocks'
},
shim: {
'angular': {exports: 'angular'},
'angular-mocks': {
deps: ['angular']
}
},
// ask Require.js to load these files (all our tests)
deps: tests,
// start test run, once Require.js is done
callback: window.__karma__.start
});
test file:
define(['angular'], function () {
describe('example test', function () {
it('should pass the test', function () {
expect(true).toBe(true);
})
});
});
When i try to run this, I get this error message:
PhantomJS 1.9.1 (Windows 7): Executed 0 of 0 SUCCESS (0 secs / 0 secs)
PhantomJS 1.9.1 (Windows 7) ERROR
Error: Script error for: angular
http://requirejs.org/docs/errors.html#scripterror
at C:/workspaces/trunk/pearl/client/node_modules/karma-requirejs/lib/require.js:138
PhantomJS 1.9.1 (Windows 7): Executed 0 of 0 ERROR (0.06 secs / 0 secs)
All files loaded as you can see here:
C:\workspaces\trunk\pearl\client\example>grunt test
Running "karma:unit" (karma) task
DEBUG [plugin]: Loading karma-* from C:\workspaces\trunk\pearl\client\node_modules
DEBUG [plugin]: Loading plugin C:\workspaces\trunk\pearl\client\node_modules/karma-chrome-launcher.
DEBUG [plugin]: Loading plugin C:\workspaces\trunk\pearl\client\node_modules/karma-coffee-preprocessor.
DEBUG [plugin]: Loading plugin C:\workspaces\trunk\pearl\client\node_modules/karma-firefox-launcher.
DEBUG [plugin]: Loading plugin C:\workspaces\trunk\pearl\client\node_modules/karma-html2js-preprocessor.
DEBUG [plugin]: Loading plugin C:\workspaces\trunk\pearl\client\node_modules/karma-jasmine.
DEBUG [plugin]: Loading plugin C:\workspaces\trunk\pearl\client\node_modules/karma-phantomjs-launcher.
DEBUG [plugin]: Loading plugin C:\workspaces\trunk\pearl\client\node_modules/karma-requirejs.
DEBUG [plugin]: Loading plugin C:\workspaces\trunk\pearl\client\node_modules/karma-script-launcher.
DEBUG [plugin]: Loading inlined plugin (defining ).
INFO [karma]: Karma v0.10.2 server started at http://localhost:9876/
INFO [launcher]: Starting browser PhantomJS
DEBUG [launcher]: Creating temp dir at C:\Users\nirk\AppData\Local\Temp\karma-30300678
DEBUG [launcher]: C:\Program Files (x86)\phantomjs\phantomjs.exe C:\Users\nirk\AppData\Local\Temp\karma-30300678/capture.js
DEBUG [watcher]: Resolved files:
C:/workspaces/trunk/pearl/client/node_modules/karma-requirejs/lib/require.js
C:/workspaces/trunk/pearl/client/node_modules/karma-requirejs/lib/adapter.js
C:/workspaces/trunk/pearl/client/node_modules/karma-jasmine/lib/jasmine.js
C:/workspaces/trunk/pearl/client/node_modules/karma-jasmine/lib/adapter.js
C:/workspaces/trunk/pearl/client/components/angular/angular.js
C:/workspaces/trunk/pearl/client/example/welcomeScreen/welcomScreenSpec.js
C:/workspaces/trunk/pearl/client/example/test-main.js
Why does the angularjs shows an error?

PhantomJS and Karma, Selector [ng\:model="query.name"] did not match any elements

When executing a karma runner using the PhantomJS browser the following error is produced:
*Selector [ng\:model="query.name"] did not match any elements*.
When executing with Chrome everything is working as expected.
Here's the line that should be matched:
`<input size='' style='width:3em;' ng-model="query.name" ng-change=changeQuery() ng-focus=focus($index) ng-blur=loseFocus($index)>`
karma.conf:
module.exports = function(config) {
config.set({
basePath: '../..',
frameworks: ['ng-scenario'],
plugins : [
'karma-ng-scenario',
'karma-chrome-launcher',
'karma-phantomjs-launcher',
'karma-junit-reporter'
],
files: [
'test/webapp/app/e2e/*.js'
],
exclude: [
],
proxies : {
'/': 'http://localhost:19880'
},
reporters: ['progress', 'junit'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: [ 'Chrome', 'PhantomJS'],
captureTimeout: 60000,
singleRun: false
});
NodeJS version: v0.10.17
Karma version: 0.10.2
PhantomJS version: 1.9
The root cause of the failure was that the PhantomJS is built with an old version of JavaScript that is missing the "bind" implementation (Why PhantomJS doesn't have Function.prototype.bind)
The controller logic was using currying, with the bind method, and thus caused the page render incorrectly. I found this out when exporting a rendered page with the phantomJS browser.
I removed all the bind method calls from the controller code and End2end test(s) are now passing as as expected.
I apologize that from the information that I have provided for the issue, it is impossible to deduct the problem cause.

AngularJS - Karma (e2e) : Executed 0 of 0 ERROR

I am experiencing a problem which I could not solve for some time, and getting very frustrating since I don't have an idea what I am doing wrong in it. :) Any help is much appreciated. I am using requirejs in my applications as well. This is basically what I am trying to build; https://github.com/Cengizism/base
When I try to start my e2e test I get this on my console;
INFO [karma]: Karma v0.10.0 server started at http://localhost:8080/_karma_/
INFO [launcher]: Starting browser Chrome
INFO [Chrome 28.0.1500 (Mac OS X 10.8.4)]: Connected on socket id n-0AVRliCogs2nWBfgDz
Chrome 28.0.1500 (Mac OS X 10.8.4): Executed 0 of 0 ERROR (0.208 secs / 0 secs)
My configuration file looks like this;
module.exports = function(karma) {
'use strict';
karma.set({
frameworks: ['jasmine', 'ng-scenario'],
files: [
'app/vendors/angular-scenario/angular-scenario.js',
'test/e2e/*.js'
],
basePath: '',
exclude: [],
reporters: ['progress'],
port: 8080,
runnerPort: 9100,
colors: true,
logLevel: karma.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
captureTimeout: 5000,
singleRun: false,
proxies: {
'/': 'http://localhost:9000/'
},
urlRoot: '/_karma_/',
plugins: [
'karma-jasmine',
'karma-ng-scenario',
'karma-chrome-launcher',
'karma-firefox-launcher',
'karma-phantomjs-launcher'
]
});
};
and finally the spec file;
describe('Simple E2e Test', function()
{
it('Should open the front page and check', function()
{
browser().navigateTo('/#/partial1');
sleep(1);
expect(element('#test').html()).toEqual('Hi testUser1');
});
});
Maybe this could help you:
To fix it, the following line should be included in karma.conf.js
exclude: ['app/lib/angular/angular-scenario.js'],
Source : https://github.com/angular/angular-phonecat/issues/71
I'm not exactly clear on this either, but after running into this issue I removed the file angular-scenario from loading and was able to get the tests to run. I believe the problem is the difference between unit testing and e2e testing configuration.
I had this same error, and it went away once I started adding some tests. Is it possible the error just means there aren't any tests present?
It could be due to the relative paths you add in files [] which may be wrong.
I had the same error, and after it works fine !
In my case, the module format was wrong in a shim file that was only used by karma. I changed the format to 'register' to support SystemJS modules, per the documentation found here.
System.config({
packages: {
'base/dist/client': {
warnings: true,
defaultExtension: 'js',
format: 'register',
map: { }
}
}
});
This is what the TS output looked like. I have to assume that these tests were wrapped as system modules, so they were not loading properly. In other words, the error resulted from no tests running.
System.register(['angular2/testing', "./data-pipe"], function(exports_1) {
var testing_1, data_pipe_1;
return {
setters:[
function (testing_1_1) {
testing_1 = testing_1_1;
}
]
// yada, yada, yada..
}
}
});

Resources