I have been trying to setup the Karma config for a new angular project that uses the Angular Deferred Bootstrap to load a config file (JSON). When Karma loads it gives me errors that it cannot find the app.json file.
Here is my angular module.
angular.module('CareerPortal', ['ngAnimate', 'ngCookies', 'ngTouch', 'ngSanitize']);
// Defer the application until we have the configuration for the app!
deferredBootstrapper.bootstrap({
element: document.body,
module: 'MyApp',
resolve: {
configuration: ['$http', function ($http) {
return $http.get('app.json');
}]
}
});
Here is my karma config
function listFiles() {
var wiredepOptions = _.extend({}, conf.wiredep, {
dependencies: true,
devDependencies: true
});
return wiredep(wiredepOptions).js
.concat([
path.join(conf.paths.tmp, '/serve/app/index.module.js'),
path.join(conf.paths.src, '/**/*.spec.js'),
path.join(conf.paths.src, '/**/*.mock.js'),
path.join(conf.paths.src, '/**/*.html')
]);
}
module.exports = function (config) {
var configuration = {
files: listFiles(),
singleRun: true,
autoWatch: false,
debug: true,
frameworks: ['jasmine'],
ngHtml2JsPreprocessor: {
stripPrefix: 'src/',
moduleName: 'CareerPortal'
},
browsers: ['PhantomJS'],
plugins: [
'karma-phantomjs-launcher',
'karma-jasmine',
'karma-ng-html2js-preprocessor'
],
preprocessors: {
'src/**/*.html': ['ng-html2js']
}
};
config.set(configuration);
};
And then the JSON file is just a standard JSON file.
Here is the error that I get
INFO [karma]: Karma v0.12.37 server started at http://localhost:9876/
INFO [launcher]: Starting browser PhantomJS
INFO [PhantomJS 1.9.8 (Mac OS X 0.0.0)]: Connected on socket 6MHhNTNq1d3djLp7R0z3 with id 21194787
WARN [web-server]: 404: /app.json
PhantomJS 1.9.8 (Mac OS X 0.0.0): Executed 0 of 0 ERROR (0.001 secs / 0 secs)
[18:23:44] Finished 'test' after 1.71 s
Related
I am trying to write unit tests for my reactjs code using Jasmine with the Karma test runner - automated with gulp. I am having an issue where my test spec includes import statements which are then not being picked up by the test body.
Here is my test spec:
import React from 'react';
import Utils from 'react-dom/test-utils';
import {MyClass} from "../Path/MyCodeFile.jsx";
describe('MyClass', function () {
it('can render without error', function () {
var component;
var element = React.createElement(
MyClass,
{}
);
expect(function () {
component = Utils.renderIntoDocument(element);
}).not.toThrow();
});
})
My Karma config file:
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
files: [
'spec/*[Ss]pec.js',
'wwwroot/js/site.js'
],
exclude: [
],
preprocessors: {
'spec/*[Ss]pec.js': ['babel']
},
babelPreprocessor: {
options: {
presets: ['es2015', 'env'],
plugins: ["transform-es2015-modules-umd"]
}
},
reporters: ['progress', 'junit'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: ['Chrome'],
plugins: [
'karma-jasmine',
'karma-junit-reporter',
'karma-chrome-launcher',
'karma-babel-preprocessor'
],
singleRun: true,
concurrency: Infinity
});
}
My gulp task:
var gulp = require('gulp');
var Server = require('karma').Server;
gulp.task('unittest', function (done) {
new Server({
configFile: __dirname + '/karma.conf.js',
singleRun: true
}, function () {
done();
}).start();
});
And this is the message I get when running the task:
[21:17:11] Starting 'unittest'...
02 08 2018 21:17:13.030:INFO [karma]: Karma v2.0.5 server started at http://0.0.0.0:9876/
02 08 2018 21:17:13.030:INFO [launcher]: Launching browser Chrome with unlimited concurrency
02 08 2018 21:17:13.046:INFO [launcher]: Starting browser Chrome
02 08 2018 21:17:14.969:INFO [Chrome 67.0.3396 (Windows 10 0.0.0)]: Connected on socket peUBczU20NB36DSvAAAA with id 73989234
Chrome 67.0.3396 (Windows 10 0.0.0): Executed 0 of 1 SUCCESS (0 secs / 0 secs)
Chrome 67.0.3396 (Windows 10 0.0.0) MyClass can render without error FAILED
TypeError: Cannot read property 'createElement' of undefined
at <Jasmine>
at UserContext.<anonymous> (spec/applicationSpec.js:31:43)
at <Jasmine>
Chrome 67.0.3396 (Windows 10 0.0.0): Executed 1 of 1 (1 FAILED) (0 secs / 0.003 secs)
Chrome 67.0.3396 (Windows 10 0.0.0): Executed 1 of 1 (1 FAILED) ERROR (0.02 secs / 0.003 secs)
[21:17:15] Finished 'unittest' after 3.6 s
It's as if the import statement isn't there.
After some pain, I have found an alternative approach which successfully runs the tests. My new test spec:
describe('MyClass', function () {
var React;
var Utils;
var MyClasses;
beforeAll(() => {
React = require("react");
Utils = require("react-dom/test-utils");
MyClasses = require("../Path/MyClass.jsx");
});
it('can render without error', function () {
var component;
var element = React.createElement(
MyClasses.MyClass,
{}
);
expect(function () {
component = Utils.renderIntoDocument(element);
}).not.toThrow();
});
})
and my updated Karma config:
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', 'browserify'],
files: [
'spec/*[Ss]pec.js',
'wwwroot/js/site.js'
],
exclude: [
],
preprocessors: {
'spec/*[Ss]pec.js': ['browserify']
},
browserify: {
debug: true,
transform: [
['babelify', {
presets: [
"#babel/preset-env",
"#babel/preset-react"
]
}]
],
extensions: ['.jsx']
},
reporters: ['progress', 'junit'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: ['Chrome'],
plugins: [
'karma-jasmine',
'karma-junit-reporter',
'karma-chrome-launcher',
'karma-babel-preprocessor',
'karma-browserify'
],
singleRun: true,
concurrency: Infinity
});
}
I have an Angular app with a Django back end. I am just starting with Karma and Jasmine unit testing. I am unable to inject my factory into my test suite. Is there any suggestions or glaring errors that I am making?
Here are my files...
karma.conf.js file
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
files: [
'./node_modules/angular/angular.js',
'./node_modules/angular-ui-router/release/angular-ui-router.js',
'./node_modules/angular-mocks/angular-mocks.js',
'./fake/path/fake/js/directory/src/modules.js',
'./fake/path/fake/js/directory/src/factories/projectinfostorage.js',
'./fake/path/fake/js/directory/src/factories/projectinfostorage.spec.js',
],
exclude: [
],
preprocessors: {
},
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
concurrency: Infinity
})
}
Angular module...
var app = angular.module("tablebrowser", ["ngRoute"]);
Factory...
app.factory('projectInfoStorage', function(){
var factory = {};
return factory;
})
Factory Unit Test...
describe('projectInfoStorage factory', function() {
var projectInfoStorage;
beforeEach(angular.mock.module('tablebrowser'));
beforeEach(inject(function(_projectInfoStorage_) {
projectInfoStorage = _projectInfoStorage_;
}));
console.log(projectInfoStorage)
});
Karma shows me this in the command line...
Chrome 55.0.2883 (Mac OS X 10.10.5) LOG: undefined
Chrome 55.0.2883 (Mac OS X 10.10.5): Executed 0 of 0 SUCCEChrome 55.0.2883 (Mac OS X 10.10.5): Executed 0 of 0 ERROR (0 secs / 0 secs)
The reason your test doesn't work is because you haven't actually tested anything. Within that describe function you need to actually put the test in an it function. Something like below:
describe('projectInfoStorage factory', function() {
var projectInfoStorage;
beforeEach(angular.mock.module('tablebrowser'));
beforeEach(inject(function(_projectInfoStorage_) {
projectInfoStorage = _projectInfoStorage_;
}));
it('will test factory', function() {
expect(true).toBeTruthy();
}
});
You need to build your tests with these in order to test something.
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.
I keep trying to run some E2E tests out of ToT angular-seed master and keep getting the following error when I run ./scripts/e2e-test.sh:
TypeError: Property 'browser' of object #<Object> is not a function
I get this error when trying to run the following piece of code as one of my e2e scenario:
'use strict';
/* https://github.com/angular/protractor/blob/master/docs/getting-started.md */
describe('MyApp', function() {
describe(Index', function() {
beforeEach(function() {
browser().navigateTo('/');
});
it('should render feature specific image', function() {
expect(element('img.featurette-image').length).toBe('4');
});
});
});
I'm wondering if my protractor config is incorrect:
exports.config = {
allScriptsTimeout: 11000,
specs: [
'../test/e2e/*.js'
],
capabilities: {
'browserName': 'chrome'
},
baseUrl: 'http://localhost:3000/',
framework: 'jasmine',
jasmineNodeOpts: {
defaultTimeoutInterval: 30000
}
};
My unit tests are running just fine. This is the Karma config I have for them (note that this is an angular app within the public director of a sinatra application listening on port 3000:
module.exports = function(config){
config.set({
basePath : '../',
files : [
'https://code.jquery.com/jquery-1.10.2.min.js',
'app/lib/angular/angular.js',
'app/lib/angular/angular-*.js',
'test/lib/angular/angular-mocks.js',
'app/js/**/*.js',
'test/unit/**/*.js'
],
exclude : [
'app/lib/angular/angular-loader.js',
'app/lib/angular/*.min.js',
'app/lib/angular/angular-scenario.js'
],
autoWatch : true,
frameworks: ['jasmine'],
browsers : ['Chrome'],
plugins : [
'karma-junit-reporter',
'karma-chrome-launcher',
'karma-firefox-launcher',
'karma-jasmine'
],
junitReporter : {
outputFile: 'test_out/unit.xml',
suite: 'unit'
}
})}
Thanks for the help!
You need to change this line:
browser().navigateTo('/');
to
browser.navigateTo('/');
That's it.
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?