karma error: TypeError: Cannot set property 'results' of undefined - node.js

when trying to run PhantomJS 2.1.1 with karma 1.3.0, i get error:
[33mWARN [PhantomJS 2.1.1 (Linux 0.0.0)]: [39mDisconnected (1 times), because no message in 10000 ms.
[31mERROR [karma]: [39m[TypeError: Cannot set property 'results' of undefined]
TypeError: Cannot set property 'results' of undefined
at onBrowserComplete (/opt/jenkins/workspace/PHANTOMJS-2.1.1/Apps/InternalApp/InternalApp/node_modules/karma-html-reporter/index.js:43:25)
at null.<anonymous> (/opt/jenkins/workspace/PHANTOMJS-2.1.1/Apps/InternalApp/InternalApp/node_modules/karma/lib/events.js:14:22)
at emitOne (events.js:82:20)
at emit (events.js:169:7)
at null._onTimeout (/opt/jenkins/workspace/PHANTOMJS-2.1.1/Apps/InternalApp/InternalApp/node_modules/karma/lib/browser.js:50:15)
at Timer.listOnTimeout (timers.js:92:15)
here is my karma.conf.js
module.exports = function(config) {
var isSingleRun = false;
var pluginsToLoad = [
'karma-jasmine',
'karma-chrome-launcher',
'karma-commonjs',
'karma-phantomjs-launcher',
'karma-firefox-launcher',
'karma-coverage',
'karma-ng-html2js-preprocessor'
];
var reportersToLoad = ['progress', 'coverage'];
var browsers = ['PhantomJS'];
// turn off all pre-processors that might be interfering with line numbers in karma errors.
var sourcePreprocessors = ['coverage'];
var templatePreprocessors = ['ng-html2js'];
var codeSrc = 'src/main/core/app/';
var testSrc = 'src/test/core/';
var filesToInclude = [
'node_modules/jquery/dist/jquery.min.js',
codeSrc + 'libs/jquery-ui-1.10.4/jquery-ui-1.10.4.js',
codeSrc + 'libs/jqueryDatatables-1.9.4/jquery.dataTables.js',
'node_modules/jasmine-core/lib/jasmine-core/jasmine.js',
'node_modules/jasmine-core/lib/jasmine-core/jasmine.css',
'node_modules/jasmine-jquery/lib/jasmine-jquery.js',
codeSrc + 'libs/angular/angular.js',
codeSrc + 'libs/angular/angular-cookies.js',
'node_modules/angular-mocks/angular-mocks.js',
codeSrc + 'libs/angular/angular-resource.min.js',
codeSrc + 'libs/lodash/lodash.compat.min.js',
codeSrc + 'libs/bootstrap/*.js',
codeSrc + 'libs/moment/2.0.0/moment.min.js',
codeSrc + '../common/**/*.js',
codeSrc + 'internal/**/*.module.js',
codeSrc + 'internal/**/*.controller.js',
codeSrc + 'internal/**/*.directive.js',
codeSrc + 'internal/**/*.service.js',
codeSrc + 'internal/**/*.filter.js',
testSrc + 'shared/testUtils.js',
'src/main/webapp/app/app_templates.js',
'src/main/webapp/app/metis_templates.js'
];
var testFilesToPush = [
testSrc + 'shared/**/*.test.js',
testSrc + 'shared/**/*.mock.js',
];
function runSingleTestFile(file) {
testFilesToPush = [testSrc + '**/' + file];
}
for (var i = 0; i < process.argv.length; i++) {
var arg = process.argv[i];
switch(arg) {
case '--debug': {
sourcePreprocessors = [];
break;
}
case '--browser': {
browsers = [process.argv[++i]];
break;
}
case '--file': {
runSingleTestFile(process.argv[++i]);
break;
}
}
}
filesToInclude = filesToInclude.concat(testFilesToPush);
// determine if and set parameters for pipeline build
function isBuildMinion(argument) {
return argument === '--pipeline';
}
if (process.argv.some(isBuildMinion)) {
console.log("running in pipeline: limiting plugins and will not run continuously");
pluginsToLoad = [ 'karma-jasmine', 'karma-commonjs', 'karma-phantomjs-launcher', 'karma-ng-html2js-preprocessor','karma-coverage','karma-html-reporter' ];
isSingleRun = true;
sourcePreprocessors = ['coverage'];
reportersToLoad = ['coverage','html'];
}
config.set({
// base path, that will be used to resolve files and exclude
basePath: '',
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: filesToInclude,
// list of files to exclude
exclude: [
'client/main.js'
],
// use dots reporter, as travis terminal does not support escaping sequences
// possible values: 'dots', 'progress'
// CLI --reporters progress
reporters: reportersToLoad,
preprocessors: {
'src/main/core/app/internal/**/*.js': sourcePreprocessors,
'src/main/core/app/metis/components/**/*.js': sourcePreprocessors
},
// web server port
// CLI --port 9876
port: 9876,
// enable / disable colors in the output (reporters and logs)
// CLI --colors --no-colors
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
// CLI --log-level debug
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
// CLI --auto-watch --no-auto-watch
autoWatch: true,
coverageReporter: {
type : 'html',
dir : 'build/karma/coverage/'
},
htmlReporter: {
outputDir: 'build/karma/html', // where to put the reports
focusOnFailures: true, // reports show failures on start
},
ngHtml2JsPreprocessor: {
stripPrefix: '.*/static',
prependPrefix: '/metis',
},
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
// CLI --browsers Chrome,Firefox,Safari
browsers: browsers,
// If browser does not capture in given timeout [ms], kill it
// CLI --capture-timeout 5000
captureTimeout: 20000,
// Auto run tests on start (when browsers are captured) and exit
// CLI --single-run --no-single-run
singleRun: isSingleRun,
// report which specs are slower than 500ms
// CLI --report-slower-than 500
reportSlowerThan: 500,
plugins: pluginsToLoad
});
};
from the command line:
karma start
INFO [karma]: Karma v0.12.37 server started at http://localhost:9876/
INFO [launcher]: Starting browser PhantomJS
INFO [PhantomJS 2.1.1 (Linux 0.0.0)]: Connected on socket JfQHKGDH0YODbO1ftHs7 with id 87652824
WARN [web-server]: 404: /InternalApp/rest/toggles/ui/AnalyticsFiles
and with the pipeline option
karma start --pipeline
running in pipeline: limiting plugins and will not run continuously
INFO [karma]: Karma v0.12.37 server started at http://localhost:9876/
INFO [launcher]: Starting browser PhantomJS
INFO [PhantomJS 2.1.1 (Linux 0.0.0)]: Connected on socket 3Ic05jImtEagaUWHuVlU with id 45163428
WARN [PhantomJS 2.1.1 (Linux 0.0.0)]: Disconnected (1 times), because no message in 10000 ms.
ERROR [karma]: [TypeError: Cannot set property 'results' of undefined]
TypeError: Cannot set property 'results' of undefined
at onBrowserComplete (/opt/jenkins/workspace/PHANTOMJS-2.1.1/Apps/InternalApp/InternalApp/node_modules/karma-html-reporter/index.js:43:25)
at null.<anonymous> (/opt/jenkins/workspace/PHANTOMJS-2.1.1/Apps/InternalApp/InternalApp/node_modules/karma/lib/events.js:14:22)
at emitOne (events.js:82:20)
at emit (events.js:169:7)
at null._onTimeout (/opt/jenkins/workspace/PHANTOMJS-2.1.1/Apps/InternalApp/InternalApp/node_modules/karma/lib/browser.js:50:15)
at Timer.listOnTimeout (timers.js:92:15)

it turns out that the cause of the error was karma not finding/firing off PhantomJS, so the solution was :
sudo npm install phantomjs-prebuilt --save-dev
this is run where the %ROOT of JavaScript is located, or where package.json is located
npm link phantomjs might have worked also

Related

Protractor browser but not connecting to test url

I have windows 10 laptop. My problem is that after i run the conf.js file, browser is opening but not conneting to the test url. giving below error message.
C:\Users\acer\AppData\Roaming\npm\node_modules\protractor\FFAutomation>C:\Users\acer\AppData\Roaming\npm\protractor conf.js
Report destination: target\screenshots\Report.html
[15:59:26] I/direct - Using FirefoxDriver directly...
[15:59:26] I/launcher - Running 1 instances of WebDriver
[16:00:15] E/launcher - Timed out waiting for the WebDriver server at http://127.0.0.1:55402/hub
[16:00:15] E/launcher - Error: Timed out waiting for the WebDriver server at http://127.0.0.1:55402/hubat Error (native)
And lastly [16:00:15] E/launcher - Process exited with error code 199
enter code here
The conf.js file is given below:
var HtmlScreenshotReporter = require('protractor-jasmine2-screenshot-reporter');
var reporter = new HtmlScreenshotReporter({
dest: 'target/screenshots',
filename: 'Report.html',
reportTitle: 'Execution Report',
showSummary: true,
showQuickLinks: true,
pathBuilder: function(currentSpec, suites, browserCapabilities) {
// will return chrome/your-spec-name.png
return browserCapabilities.get('browserName') + '/' + currentSpec.fullName;
}
});
exports.config = {
directConnect: true,
//seleniumAddress: 'http://localhost:4444/wd/hub',
capabilities: {'browserName': 'firefox'},
// multiCapabilities: [
// {
// browserName: 'firefox'
// },
// {
// browserName: 'chrome'
// }
// ],
framework: 'jasmine',
specs: ['Login_spec3.js'],
//'Login_spec2.js','Article_spec.js','Catalog_spec.js', ' 'LoginwithTD_spec2.js', 'Login_spec3copy.js','Setting_spec.js'
allScriptsTimeout: 300000,
getPageTimeout: 300000,
jasmineNodeOpts: {
defaultTimeoutInterval: 300000
},
// Setup the report before any tests start
beforeLaunch: function() {
return new Promise(function(resolve){
reporter.beforeLaunch(resolve);
});
},
// Close the report after all tests finish
afterLaunch: function(exitCode) {
return new Promise(function(resolve){
reporter.afterLaunch(resolve.bind(this, exitCode));
});
},
onPrepare: function() {
var width = 1300;
var height = 1200;
browser.driver.manage().window().setSize(width,height);
jasmine.getEnv().addReporter(reporter);
afterAll(function(done) {
process.nextTick(done);
})
//browser.params.users = require('./shared.params.' + countryCode + '.json').users;
}
};
*I have copied some scripts(which is executable on her macbook) from a friend and paste it in a folderin window 10 pc named FFAutomation path. C:\Users\acer\AppData\Roaming\npm\node_modules\protractor\FFAutomation
1)I have update the chrome driver to version 2.24 chromedriver_win32 , update the chrome driver with command "webdriver-manager update" and run the webdriver with command "webdriver-manager start".
2) Than i run conf.js file on another terminal with the firefox browser
C:\Users\acer\AppData\Roaming\npm\node_modules\protractor\FFAutomation>C:\Users\ acer\AppData\Roaming\npm\protractor conf.js
I am getting this following error
Report destination: target\screenshots\Report.html
[15:59:26] I/direct - Using FirefoxDriver directly...
[15:59:26] I/launcher - Running 1 instances of WebDriver
[16:00:15] E/launcher - Timed out waiting for the WebDriver server at http://127.0.0.1:55402/hub
[16:00:15] E/launcher - Error: Timed out waiting for the WebDriver server at http://127.0.0.1:55402/hubat Error (native)
And lastly [16:00:15] E/launcher - Process exited with error code 199
enter code here
3) Than i run conf.js file on another terminal with the "chrome" browser
C:\Users\acer\AppData\Roaming\npm\node_modules\protractor\FFAutomation>C:\Users\ acer\AppData\Roaming\npm\protractor conf.js
I am getting this following error
Error: Error: Cannot find module '/Users/rohitgathibandhe/npm- global/lib/node_modules/protractor/FFAutomation/Function_Lib.js'
E/launcher - Process exited with error code 100
Run webdriver-manager start before executing your tests.

Starting Selenium Server with Nightwatch.js

I was using selenium-webdriver and wanted to try out nightwatch.js to see if it is easier to use. I followed the instructions here. I decided to let Nightwatch automatically start the selenium server for me so I did what I thought was the proper configuration based on the linked provided above. I get an error that I can't figure out and the output says:
Starting selenium server... started - PID: 1760
[Test] Test Suite
=================
Running: demoTestGoogle
Error retrieving a new session from the selenium server
Error: connect ECONNREFUSED 127.0.0.1:8080
at Object.exports._errnoException (util.js:856:11)
at exports._exceptionWithHostPort (util.js:879:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1053:14)
Connection refused! Is selenium server started?
Process finished with exit code 1
The selenium debug log file says this
13:43:03.394 INFO - Launching a standalone Selenium Server
13:43:03.474 INFO - Java: Oracle Corporation 25.73-b02
13:43:03.474 INFO - OS: Windows 7 6.1 amd64
13:43:03.483 INFO - v2.52.0, with Core v2.52.0. Built from revision 4c2593c
13:43:03.530 INFO - Driver class not found: com.opera.core.systems.OperaDriver
13:43:03.530 INFO - Driver provider com.opera.core.systems.OperaDriver is not registered
13:43:03.536 INFO - Driver provider org.openqa.selenium.safari.SafariDriver registration is skipped:
registration capabilities Capabilities [{browserName=safari, version=, platform=MAC}] does not match the current platform VISTA
13:43:03.665 INFO - RemoteWebDriver instances should connect to: http://127.0.0.1:4444/wd/hub
13:43:03.665 INFO - Selenium Server is up and running
This is my nightwatch.json file
{
"src_folders": [ "tests" ],
"output_folder": "reports",
"custom_commands_path": "",
"custom_assertions_path": "",
"page_objects_path": "",
"globals_path": "",
"selenium": {
"start_process": true,
"server_path": "./bin/selenium-server-standalone-jar/jar/selenium-server-standalone-2.52.0.jar",
"start_session" : true,
"log_path": "",
"host": "",
"port": 4444,
"cli_args": {
"webdriver.chrome.driver": "",
"webdriver.ie.driver": ""
}
},
"test_settings": {
"default": {
"launch_url": "http://localhost",
"selenium_port": 8080,
"selenium_host": "localhost",
"silent": true,
"screenshots": {
"enabled": false,
"path": ""
},
"desiredCapabilities": {
"browserName": "firefox",
"javascriptEnabled": true,
"acceptSslCerts": true
}
},
"chrome": {
"desiredCapabilities": {
"browserName": "chrome",
"javascriptEnabled": true,
"acceptSslCerts": true
}
}
}
}
Edit: Added demoTestGoogle, I have a nightwatch.js file in which I run and then it runs the demoTestGoogle function.
nightwatch.js which runs demoTestGoogle
require('nightwatch/bin/runner.js');
demoTestGoogle function in separate JS file
this.demoTestGoogle = function (browser) {
browser
.url('http://www.google.com')
.waitForElementVisible('body', 1000)
.setValue('input[type=text]', 'nightwatch')
.waitForElementVisible('button[name=btnG]', 1000)
.click('button[name=btnG]')
.pause(1000)
.assert.containsText('#main', 'The Night Watch')
.end();
};
As suggested by this great guide to Nightwatch, dwyl-learn-nightwatch, you can replace your nightwatch.json file with a .js file to add features like variables, globals and even requiring in Selenium so Nightwatch can see it and run it.
Here's a simple example I modified from that GitHub source to start selenium with its tests. Make sure to install the dependencies in the project, first:
npm install --save-dev nightwatch chromedriver selenium-server
Then replace that JSON file with a .js one, perhaps named nightwatch.conf.js and notice the config options under the selenium key in the config file:
nightwatch.conf.js
const seleniumServer = require("selenium-server");
const chromedriver = require("chromedriver");
const SCREENSHOT_PATH = "./screenshots/";
module.exports = {
"src_folders": [
"tests/e2e"
],
"output_folder": "./reports",
"selenium": {
"start_process": true, // tells nightwatch to start/stop the selenium process
"server_path": seleniumServer.path,
"host": "127.0.0.1",
"port": 4444, // standard selenium port
"cli_args": {
"webdriver.chrome.driver" : chromedriver.path
}
},
"test_settings": {
"default": {
"screenshots": {
"enabled": true, // if you want to keep screenshots
"path": SCREENSHOT_PATH // save screenshots here
},
"globals": {
"waitForConditionTimeout": 5000 // set a (default) timeout period, maybe 5s
},
"desiredCapabilities": { // use Chrome as the default browser for tests
"browserName": "chrome"
}
},
"chrome": {
"desiredCapabilities": {
"browserName": "chrome",
"javascriptEnabled": true
}
}
}
}
function padLeft (count) { // theregister.co.uk/2016/03/23/npm_left_pad_chaos/
return count < 10 ? '0' + count : count.toString();
}
var FILECOUNT = 0; // "global" screenshot file count
/**
* The default is to save screenshots to the root of your project even though
* there is a screenshots path in the config object above! ... so we need a
* function that returns the correct path for storing our screenshots.
* While we're at it, we are adding some meta-data to the filename, specifically
* the Platform/Browser where the test was run and the test (file) name.
*/
function imgpath (browser) {
var a = browser.options.desiredCapabilities;
var meta = [a.platform];
meta.push(a.browserName ? a.browserName : 'any');
meta.push(a.version ? a.version : 'any');
meta.push(a.name); // this is the test filename so always exists.
var metadata = meta.join('~').toLowerCase().replace(/ /g, '');
return SCREENSHOT_PATH + metadata + '_' + padLeft(FILECOUNT++) + '_';
}
module.exports.imgpath = imgpath;
module.exports.SCREENSHOT_PATH = SCREENSHOT_PATH;
And the command I use to run this is this, using the locally installed nightwatch version:
nightwatch --config nightwatch.conf.js
Hope that helps!
Goodluck and good on your for testing your code.

Karma/Jasmine tests fail with error: 'Uncaught Error: Module name "simple_test.js" has not been loaded yet for context: _. Use require([])'

I am using Karma and Jasmine to run tests on my project built with React. When I try to run my Karma tests I get this error in the console:
Running "karma:test" (karma) task
WARN `start` method is deprecated since 0.13. It will be removed in 0.14. Please use
server = new Server(config, [done])
server.start()
instead.
07 09 2015 14:46:56.552:WARN [plugin]: Error during loading "karma-opera-launcher" plugin:
ENOENT, no such file or directory './config/prefs.ini'
Hash: 8344a6c0a9b3c44a5636
Version: webpack 1.12.1
Time: 6ms
webpack: bundle is now VALID.
07 09 2015 14:46:56.685:INFO [karma]: Karma v0.13.9 server started at http://localhost:9876/
07 09 2015 14:46:56.689:INFO [launcher]: Starting browser Chrome
07 09 2015 14:46:56.700:INFO [launcher]: Starting browser Firefox
07 09 2015 14:46:56.713:INFO [launcher]: Starting browser PhantomJS
07 09 2015 14:46:57.063:INFO [PhantomJS 1.9.8 (Linux 0.0.0)]: Connected on socket X4i_xm1JTKdTSJO2AAAA with id 74978391
PhantomJS 1.9.8 (Linux 0.0.0) ERROR
Error: Module name "simple_test.js" has not been loaded yet for context: _. Use require([])
http://requirejs.org/docs/errors.html#notloaded
at /home/michael/repository/short-stories/node_modules/requirejs/require.js:140
07 09 2015 14:46:58.890:INFO [Chromium 44.0.2403 (Ubuntu 0.0.0)]: Connected on socket K4FoGDjsszglqxvVAAAB with id 26278080
Chromium 44.0.2403 (Ubuntu 0.0.0) ERROR
Uncaught Error: Module name "simple_test.js" has not been loaded yet for context: _. Use require([])
http://requirejs.org/docs/errors.html#notloaded
at /home/michael/repository/short-stories/node_modules/requirejs/require.js:140
07 09 2015 14:47:02.441:INFO [Firefox 40.0.0 (Ubuntu 0.0.0)]: Connected on socket EJQMu5bHS1DnJLRXAAAC with id 52731426
Firefox 40.0.0 (Ubuntu 0.0.0) ERROR
Error: Module name "simple_test.js" has not been loaded yet for context: _. Use require([])
http://requirejs.org/docs/errors.html#notloaded
at /home/michael/repository/short-stories/node_modules/requirejs/require.js:165
Warning: Task "karma:test" failed. Use --force to continue.
I have tried the recommendations at http://requirejs.org/docs/errors.html#notloaded, but it didn't change the error. I also tried making my require statements into one big callback hell, but it didn't fix the issue. I'm sure the problem is that it's trying to run the tests before loading the modules, but if I can't make it wait by using callbacks, I'm not sure how to deal with the issue. Any help would be greatly appreciated, Thanks in advance.
I'll paste my karma.conf.js, story_test.js, and test_entry.js files below. Let me know if there is more info that will help. You can view the full project on my GitHub Repo.
Here's my karam.conf.js:
// Karma configuration
// Generated on Thu Jul 02 2015 15:56:34 GMT-0700 (PDT)
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', 'requirejs'],
// list of files / patterns to load in the browser
files: [
__dirname + '/node_modules/phantomjs-polyfill/bind-polyfill.js',
__dirname + '/node_modules/requirejs/require.js',
__dirname + '/node_modules/karma-requirejs/lib/adapter.js',
__dirname + '/test/karma_tests/*entry.js'
],
//plugins to start browsers
plugins : [
'karma-junit-reporter',
'karma-phantomjs-launcher',
'karma-chrome-launcher',
'karma-firefox-launcher',
'karma-opera-launcher',
'karma-ie-launcher',
'karma-jasmine',
'karma-chai',
'karma-webpack',
'karma-requirejs',
'karma-script-launcher'
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'test/karma_tests/*test.js': ['webpack'],
// 'test/**/*_test.js': ['webpack']
},
webpack: {
// karma watches the test entry points
// (you don't need to specify the entry option)
// webpack watches dependencies
// webpack configuration
module: {
loaders: [{
test: /\.jsx$/,
loader:'jsx-loader'
}]
}
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// 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: false,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['Chrome', 'Firefox', 'PhantomJS'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: true,
// Set timeout to 100 seconds
// browserNoActivityTimeout: 100000
});
};
Here's my story_test.js:
'use strict';
var React = require('react/addons');
var Story = require('../../app/js/components/story.jsx');
var TestUtils = React.addons.TestUtils;
var testUtilsAdditions = require('react-testutils-additions');
describe('Story component', function () {
var component;
beforeEach(function () {
var element = React.createElement(Story);
element.props.data = {
storyTitle: 'front end test title',
author : 'front end author',
storyText : 'front end story text'
};
component = TestUtils.renderIntoDocument(element);
});
it('should display a story', function () {
expect(component.props.data).toBeDefined();
expect(component.props.data.storyTitle).toBeDefined();
expect(component.props.data.storyTitle).toBe('front end test title');
expect(component.props.data.author).toBe('front end author');
expect(component.props.data.storyText).toBe('front end story text');
});
});
And finally here's the test_entry.js:
'use strict';
require('./simple_test.js');
require('./story_test.js');
The error seems to come from the http://requirejs.org project and I think is trying to get you to change from using synchronous CommonJS require calls such as;
require('./simple_test.js');
require('./story_test.js');
to asynchronous AMD calls such as;
require(['./simple_test.js', './story_test.js'], function() {
// simple_test and story_test are now loaded
});
It's not clear to me from what you've posted which modules are requirejs/AMD and which aren't, it looks like you may possibly have a confusing mixture of the two? Sorry I can't help much more than this.

E2E Testing Angular with Karma - ng-scenario 'Module is not defined'

I've been trying to run some e2e tests with Karma.
It's not working for me at all.
Right now I'm getting the following error:
Firefox 28.0.0 (Windows 7) ERROR
ReferenceError: module is not defined
at C:/MYPATH/Test/node_modules/karma-ng-scenario/lib/ind
ex.js:12
Firefox 28.0.0 (Windows 7) ERROR
ReferenceError: browser is not defined
at C:/MYPATH/Test/e2e/scenarios.js:12
My config file looks like this:
module.exports = function(config){
config.set({
basePath : './',
frameworks: ['ng-scenario'],
files : [
'./node_modules/karma-ng-scenario/lib/*.js',
'./e2e/*.js'
],
autoWatch : true,
singleRun : true,
browsers : ['Firefox'],
plugins : [
'karma-ng-scenario',
'karma-chrome-launcher',
'karma-firefox-launcher'
],
junitReporter : {
outputFile: 'test_out/unit.xml',
suite: 'unit'
},
urlRoot : '/__karma/',
proxies : {
'/public/' : 'http://localhost:8080'
}
});
};
My scenarios file just tests to see if the base path redirects.
I've already done a lot of messing with npm to get to this point, most recently "npm install karma-ng-scenario --save-dev" but no luck unfortunately.
In files[] specify path to angular.js as a very first, then any other angular modules you use (angular-mocks.js, angular-resource.js, angular-cookies.js), then any library you use, then your own code.
In files:[...] array you have to specify all the files that contain the actual code to which you are writing tests, if your module is using other modules, then you should add files of all the modules on which your module depends.
suppose you are testing 'someModule' module you have to include the 'someModule' controllers, views, services, directives and other modules if your module depends on them
Note: Assuming your files are in their specific directories
files: [
... //angularjs, angular-mocks, karma, protractor and other files you need
...
'scripts/someModule/controllers/*.js',
'scripts/someModule/services/*.js',
'scripts/someModule/directives/*.js',
'views/someModule/*.html'
]
or simply
files: [
... //angularjs, angular-mocks, karma, protractor and other files you need
...
'scripts/someModule/**/*.js',
'views/someModule/*.html'
]
And make sure to install and include all the testing libraries you depend on (i.e, angularjs, angular-mocks, protrator, karma etc) in the files array
So the configuration I finally got my E2E tests to work with was this:
// Karma configuration
// Generated on Fri Apr 11 2014 02:35:20 GMT+0800 (China Standard Time)
module.exports = function(config) {
config.set({
// base path, that will be used to resolve files and exclude
basePath: '..',
// frameworks to use
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
ANGULAR_SCENARIO,
ANGULAR_SCENARIO_ADAPTER,
'test/e2e/*.js',
],
// list of files to exclude
exclude: [
],
// test results reporter to use
// possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
reporters: ['progress'],
// 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, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera (has to be installed with `npm install karma-opera-launcher`)
// - Safari (only Mac; has to be installed with `npm install karma-safari-launcher`)
// - PhantomJS
// - IE (only Windows; has to be installed with `npm install karma-ie-launcher`)
//browsers: ['PhantomJS', 'Firefox', 'Chrome'],
browsers: ['Firefox', 'Chrome'],
// If browser does not capture in given timeout [ms], kill it
captureTimeout: 60000,
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false,
proxies : {
"/": "http://localhost:8080"
},
urlRoot : "/__karma/"
});
};
It seems that a better solution for running end to end tests is to use protractor. NG-SCENARIO is depreciated and will cause warnings but this should still run. https://github.com/angular/protractor

Is it possible to use CommonJS modules with karma/mocha

Is this possible with CommonJS?
Basically I'm trying to take the API testing from http://thewayofcode.wordpress.com/2013/04/21/how-to-build-and-test-rest-api-with-nodejs-express-mocha/
and use Karma to run the tests.
I'm attempted to use RequireJS with karma, based off http://karma-runner.github.io/0.10/plus/requirejs.html
My package.json is correctly setup and 'npm install' gets everything I need,
but when I do 'karma start test/karma.conf.js' , no tests run
DEBUG [karma]: All browsers are ready, executing
DEBUG [web-server]: serving: /home/npoklitar/project/node_modules/karma/static/context.html
DEBUG [web-server]: serving: /home/npoklitar/project/node_modules/karma-requirejs/lib/require.js
DEBUG [web-server]: serving: /home/npoklitar/project/node_modules/karma-requirejs/lib/adapter.js
DEBUG [web-server]: serving: /home/npoklitar/project/node_modules/mocha/mocha.js
DEBUG [web-server]: serving: /home/npoklitar/project/node_modules/karma-mocha/lib/adapter.js
DEBUG [web-server]: serving: /home/npoklitar/project/test/routerSpec.js
DEBUG [web-server]: serving: /home/npoklitar/project/test/test-main.js
ERROR: 'There is no timestamp for /base/supertest.js!'
Chrome 30.0.1599 (Linux): Executed 0 of 0 SUCCESS (0 secs / 0 secs)
ERROR: 'There is no timestamp for /base/should.js!'
Chrome 30.0.1599 (Linux): Executed 0 of 0 SUCCESS (0 secs / 0 secs)
ERROR: 'There is no timestamp for /base/assert.js!'
Chrome 30.0.1599 (Linux): Executed 0 of 0 SUCCESS (0 secs / 0 secs)
Chrome 30.0.1599 (Linux): Executed 0 of 0 ERROR (0.355 secs / 0 secs)
DEBUG [launcher]: Disconnecting all browsers
DEBUG [launcher]: Killing Chrome
test/rounterSpec.js
require(['supertest','should','assert'], function(supertest,should,assert){
describe('Routing:', function() {
var url = 'http://localhost:16000';
describe('API', function() {
it('should return the success string and request headers', function(done){
supertest(url)
.get('/api')
.expect(200)
.end(function(err, res) {
if (err) {
throw err;
}
var text = res.text;
var splitted = text.split('!');
splitted[0].should.include('request successfully proxied to API');
done();
});
});
});
});
});
test/karma.conf.js
module.exports = function (karma) {
karma.set({
// base path, that will be used to resolve files and exclude
basePath: '../',
frameworks: ['mocha','requirejs'],
// list of files / patterns to load in the browser
files: [
// {pattern: 'node_modules/chai/chai.js', include: true},
// {pattern: '*.js', include: false},
'test/*.js',
'test/test-main.js'
],
// list of files to exclude
exclude: [
'karma.conf.js'
],
// use dots reporter, as travis terminal does not support escaping sequences
// possible values: 'dots', 'progress', 'junit', 'teamcity'
// CLI --reporters progress
reporters: ['progress', 'junit', 'coverage'],
junitReporter: {
// will be resolved to basePath (in the same way as files/exclude patterns)
outputFile: 'junit-report/test-results.xml'
},
preprocessors: {
'src/*.js': 'coverage'
},
//Code Coverage options. report type available:
//- html (default)
//- lcov (lcov and html)
//- lcovonly
//- text (standard output)
//- text-summary (standard output)
//- cobertura (xml format supported by Jenkins)
coverageReporter: {
// cf. http://gotwarlost.github.com/istanbul/public/apidocs/
type: 'lcov',
dir: 'coverage/'
},
// web server port
port: 9876,
// cli runner port
runnerPort: 9100,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel: LOG_DEBUG,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
// CLI --browsers Chrome,Firefox,Safari
browsers: ['Chrome'],
// If browser does not capture in given timeout [ms], kill it
captureTimeout: 6000,
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: true,
plugins: [
'karma-mocha',
'karma-chrome-launcher',
'karma-firefox-launcher',
'karma-junit-reporter',
'karma-coverage',
'karma-requirejs'
]
});
}
test/test-main.js
var tests = [];
for (var file in window.__karma__.files) {
if (/Spec\.js$/.test(file)) {
tests.push(file);
}
}
requirejs.config({
// Karma serves files from '/base'
baseUrl: '/base',
/*
paths: {
'jquery': '../lib/jquery',
'underscore': '../lib/underscore',
},
shim: {
'underscore': {
exports: '_'
}
},
*/
// nodeRequire: require, //doesnt work with or without this commented
// ask Require.js to load these files (all our tests)
deps: tests,
// start test run, once Require.js is done
callback: window.__karma__.start
});
I've created a plugin for Karma here: https://www.npmjs.com/package/karma-common-js
It let's you write tests as if you're using Browserify, but the plugin doesn't use Browserify. Not using Browserify has a few advantages:
There's no bundle created, so it's very fast for watching file changes
Line numbers and file names are preserved in stack traces without needing source maps
Works with karma-coverage
Lets you pass a second argument to require to pass in mocks
All (I hope) of Browserifys core features work. Such as transforms, respecting the browser field in package.json, requiring builtin modules uses the same shims as Browserify, etc.
There is now a CommonJS plugin for Karma: https://github.com/karma-runner/karma-commonjs
After trying a bunch of different plugins, I ended up using the karma-browserifast plugin that actually works quite well - especially if you run it in debug mode.

Resources