Protractor browser but not connecting to test url - node.js

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.

Related

Prtractor Error with Gitlab CI/CD Pipeline

We have a secured network and Protractor test suite runs locally. But when running the Gitlab CI/CD pipeline with headless chrome it returns network errors
This is my conf.js
exports.config = {
framework : "jasmine2",
multiCapabilities : [
{
browserName: "chrome",
chromeOptions: {
args: [
"--incognito",
"--headless",
"--no-sandbox",
"--disable-gpu",
"--window-size=1920,1080",
"--disable-dev-shm-usage",
"--allow-insecure-localhost"
],
},
},
],
specs: [
'./tests/sample.ts',
],
seleniumServerJar: '../node_modules/protractor/node_modules/webdriver-manager/selenium/selenium-server-standalone-3.141.59.jar',
seleniumAddress: 'http://localhost:4444/wd/hub',
chromeDriver: './node_modules/protractor/node_modules/webdriver-manager/selenium/chromedriver_98.0.4758.102',
directConnect: true,
onPrepare: function(){
void browser.manage().timeouts().implicitlyWait(10000);
void browser.waitForAngularEnabled(false);
require("ts-node").register({
project: require("path").join(__dirname, "./tsconfig.json"),
})
},
plugins: [{
package: 'protractor-screenshoter-plugin',
screenshotPath: './outputJS/reports/e2e',
screenshotOnExpect: 'failure+success',
takeScreenshots:'true',
withLogs: 'true',
writeReportFreq: 'asap',
imageToAscii: 'none',
clearFoldersBeforeTest: true
}]
}
Error appears
$ npm run e2e-headless-run
> e2e#1.0.0 e2e-headless-run /var/gitlab-runner/-8xgu1of/0/team-iron/ebba/pco-front-end/e2e
> node node_modules/protractor/bin/protractor ./headless_conf.js
[09:46:36] W/driverProviders - Using driver provider directConnect, but also found extra driver provider parameter(s): seleniumAddress, seleniumServerJar
[09:46:37] I/launcher - Running 1 instances of WebDriver
[09:46:37] I/direct - Using ChromeDriver directly...
Activated Protractor Screenshoter Plugin, ver. 0.10.3 (c) 2016 - 2022 [object Object] and contributors
Started
Creating reporter at ./outputJS/reports/e2e/
FF
Failures:
1) Google Sample Test loading web page
Message:
Expected '**Network Error**' to contain 'PCO'.
Stack:
Error: Failed expectation
at helper.verifyPageTitle (/var/gitlab-runner/-8xgu1of/0/team-iron/ebba/pco-front-end/e2e/helper/helper.ts:151:36)
at loginPage.verify_page_title (/var/gitlab-runner/-8xgu1of/0/team-iron/ebba/pco-front-end/e2e/pages/loginpage.ts:55:23)
I tried adding webDriverProxy and proxy. But same result appears.

Error code 135, Error message Could not fingd update-config.json. Run webdriver-manager update to download the binaries

I am trying to execute my tests in nodejs using protractor.
Example protractor protractor.conf
When I run protractor protractor.conf, I get error Error code 135, Error message Could not fingd update-config.json. Run webdriver-manager update to download the binaries
I ran the following command but still get the above error message
webdriver-manager update -- proxy http://
protractor.conf.js
/*global jasmine */
var SpecReporter = require('jasmine-spec-reporter');
var TfsReporter = require('jasmine-tfs-reporter');
exports.config = {
allScriptsTimeout: 11000,
specs: [
'./src/tests/*spec.js'
],
capabilities: {
'browserName': 'chrome',
/*'browserName': 'phantomjs',
'phantomjs.binary.path': require('phantomjs-prebuilt').path,
'phantomjs.ghostdriver.cli.args': ['--loglevel=DEBUG']*/
},
directConnect: true,
baseUrl: 'http://localhost:4200/',
framework: 'jasmine',
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 30000,
print: function() {}
},
useAllAngular2AppRoots: false,
beforeLaunch: function() {
require('ts-node').register({
project: '../PartyAndIndustryDataMigration'
});
},
onPrepare: function() {
jasmine.getEnv().addReporter(new SpecReporter());
jasmine.getEnv().addReporter(new TfsReporter());
}
};
I'm not 100% sure (and cannot it check now), but shouldn't command look like that:
webdriver-manager update --proxy http:// (without space between -- and proxy)?
I guess chrome driver & update-config.json couldn't downloaded at the time of webdriver-manager update.
Just for verification go to
node_modules\protractor\node_modules\webdriver-manager\selenium\
location and look if everything downloaded properly?
If there is problem on downloading chrome driver you can check chrome-response.xml in same location for reason. One reason could be chrome driver website is in blacklisted or behind the proxy.
1.Open Command prompt or terminal.
2.Go to your project root directory.
3.Enter the below command and hit Enter key.
node node_modules/protractor/bin/webdriver-manager update
This command will update the WebDriver Manager.

karma error: TypeError: Cannot set property 'results' of undefined

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

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.

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