Karma run test cases double times - unit-testing

I am using karma for angular 2 unit testing.Its works fine to me but I have one thing which I don't know why its happening.With karma when I run test cases, every function which I test run two times.I knew this problem when I print console.log on that function which I used in test case.I don't know why this happened to me.Please help me.
I am using it with webpack.
webpack: bundle is now VALID.
17 10 2016 10:02:20.102:INFO [karma]: Karma v1.2.0 server started at http://localhost:9876/
17 10 2016 10:02:20.106:INFO [launcher]: Launching browser Chrome with unlimited concurrency
17 10 2016 10:02:20.188:INFO [launcher]: Starting browser Chrome
17 10 2016 10:02:40.019:INFO [Chrome 52.0.2743 (Linux 0.0.0)]: Connected on socket /#bNq05S_5S6il-eenAAAA with id 72225563
LOG: 'headers = {"content-type":["application/json"]}'
LOG: 'headers = {"content-type":["application/json"]}'
Global Service : Login Authentication
✔ Should have operator login Authentication
LOG: 'headers = {"content-type":["application/json"],"authorization":["Token ad42hjk234bad8808"]}'
LOG: 'headers = {"content-type":["application/json"],"authorization":["Token ad42hjk234bad8808"]}'
LOG: 'catch 400 = {"_body":"{\"username\":\"xyz#gmail.com\",\"password\":\"761e768a501c30ea8e38\"}","status":400,"ok":false,"statusText":null,"headers":null,"type":null,"url":null}'
LOG: 'catch 400 = {"_body":"{\"username\":\"xyz#gmail.com\",\"password\":\"761e768a501c30ea8e38\"}","status":400,"ok":false,"statusText":null,"headers":null,"type":null,"url":null}'
✔ Should be call error page if login credential wrong
Global Utils : Meta urls API
✔ Should have get Meta urls
LOG: 'page error'
LOG: 'page error'
✔ If get Empty Response of MetaUrls with status code 200
LOG: 'page error'
LOG: 'page error'
✔ If get Empty Response of MetaUrls with status code 400
LOG: 'page error'
LOG: 'page error'
✔ Should not have get Meta urls data with status code 404
Finished in 0.473 secs / 0.431 secs
SUMMARY:
✔ 6 tests completed
karma.conf.js
/**
* #author: #AngularClass
*/
module.exports = function (config) {
var testWebpackConfig = require('./config/webpack.test.js')({env: 'test'});
var configuration = {
// base path that will be used to resolve all patterns (e.g. files, exclude)
basePath: '',
/*
* Frameworks to use
*
* available frameworks: https://npmjs.org/browse/keyword/karma-adapter
*/
frameworks: ['jasmine'],
// list of files to exclude
exclude: [],
/*
* list of files / patterns to load in the browser
*
* we are building the test environment in ./spec-bundle.js
*/
files: [
{ pattern: './config/spec-bundle.js', watched: false }
],
/*
* preprocess matching files before serving them to the browser
* available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
*/
preprocessors: {
'./config/spec-bundle.js': ['coverage', 'webpack', 'sourcemap'],
},
// Webpack Config at ./webpack.test.js
webpack: testWebpackConfig,
coverageReporter: {
type: 'in-memory'
},
remapCoverageReporter: {
'text-summary': null,
json: './coverage/coverage.json',
html: './coverage/html'
},
// Webpack please don't spam the console when running in karma!
webpackMiddleware: {stats: 'errors-only'},
/*
* test results reporter to use
*
* possible values: 'dots', 'progress'
* available reporters: https://npmjs.org/browse/keyword/karma-reporter
*/
reporters: ['mocha', 'coverage', 'remap-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: false,
/*
* start these browsers
* available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
*/
browsers: [
'Chrome'
],
customLaunchers: {
ChromeTravisCi: {
base: 'Chrome',
flags: ['--no-sandbox']
}
},
plugin: [
'karma-coverage',
'karma-mocha-reporter',
'karma-remap-coverage',
'karma-sourcemap-loader',
'istanbul-instrumenter-loader'
],
/*
* Continuous Integration mode
* if true, Karma captures browsers, runs the tests and exits
*/
singleRun: true
};
if (process.env.TRAVIS) {
configuration.browsers = [
'ChromeTravisCi',
'Chrome'
];
}
config.set(configuration);
};
spec-bundle.js
/**
* #author: #AngularClass
*/
/*
* When testing with webpack and ES6, we have to do some extra
* things to get testing to work right. Because we are gonna write tests
* in ES6 too, we have to compile those as well. That's handled in
* karma.conf.js with the karma-webpack plugin. This is the entry
* file for webpack test. Just like webpack will create a bundle.js
* file for our client, when we run test, it will compile and bundle them
* all here! Crazy huh. So we need to do some setup
*/
Error.stackTraceLimit = Infinity;
require('core-js/es6');
require('core-js/es7/reflect');
// Typescript emit helpers polyfill
require('ts-helpers');
require('zone.js/dist/zone');
require('zone.js/dist/long-stack-trace-zone');
require('zone.js/dist/proxy'); // since zone.js 0.6.15
require('zone.js/dist/sync-test');
require('zone.js/dist/jasmine-patch'); // put here since zone.js 0.6.14
require('zone.js/dist/async-test');
require('zone.js/dist/fake-async-test');
// RxJS
require('rxjs/Rx');
var testing = require('#angular/core/testing');
var browser = require('#angular/platform-browser-dynamic/testing');
testing.TestBed.initTestEnvironment(
browser.BrowserDynamicTestingModule,
browser.platformBrowserDynamicTesting()
);
/*
* Ok, this is kinda crazy. We can use the context method on
* require that webpack created in order to tell webpack
* what files we actually want to require or import.
* Below, context will be a function/object with file names as keys.
* Using that regex we are saying look in ../src then find
* any file that ends with spec.ts and get its path. By passing in true
* we say do this recursively
*/
var testContext = require.context('../src', true, /\.spec\.ts/);
/*
* get all the files, for each file, call the context function
* that will require the file and load it up here. Context will
* loop and require those spec files here
*/
function requireAll(requireContext) {
return requireContext.keys().map(requireContext);
}
// requires and returns all modules that match
var modules = requireAll(testContext);

I've had the same problem and it's because the '*.spec.js' files need to be accessible but not included, so you have to do something like this:
files: [
{ pattern: './config/spec-bundle.js', watched: false },
{ pattern: '**/*.spec.js', included: false, served: true, watched: false }
]
This is the source I've found: https://medium.com/#SchizoDuckie/so-your-karma-tests-run-twice-this-is-what-you-need-to-do-be74ce9f257e#.lqrkf24ty

Related

Karma+Jasmine tests not running with Chrome, "Executed 0 of 0 ERROR"

I'm trying to test my project angular 5 with jasmine and karma but it show me this error:
myProject\Front\src\app> ng test
Your global Angular CLI version (7.0.3) is greater than your local
version (1.7.4). The local Angular CLI version is used.
To disable this warning use "ng config -g cli.warnings.versionMismatch false".
30 10 2018 09:42:25.435:WARN [karma]: No captured browser, open http://localhost:9876/
30 10 2018 09:42:38.011:INFO [karma]: Karma v0.13.9 server started at http://localhost:9876/
30 10 2018 09:42:38.016:INFO [launcher]: Starting browser Chrome
30 10 2018 09:42:41.074:INFO [Chrome 69.0.3497 (Windows 10 0.0.0)]: Connected on socket RiQkM_n-0oc-xuYAAAAA with id 49828596
Chrome 69.0.3497 (Windows 10 0.0.0) ERROR: 'DEPRECATION:', 'Setting specFilter directly on Env is deprecated, please use the specFilter option in `configure`'
Chrome 69.0.3497 (Windows 10 0.0.0): Executed 0 of 0 ERROR (0.003 secs / 0 secs)
and this is my karma.conf.js :
// Karma configuration
// Generated on Mon Oct 29 2018 16:09:43 GMT+0000 (Maroc)
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'],
//plugin needed
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
],
// list of files / patterns to load in the browser
files: [
'src/app/*.spec.ts',
],
// list of files / patterns to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
},
// 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: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['Chrome'],
// 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
})
}
and this the interface in Google Chrome:
I'm just a beginner 😄 and I'm not sure if those informations are enough. I tried a lot of solutions that I found but always the same problem. Can someone help me?
This is a result of an incompatibility with newer versions of Chrome (failing for me with version 70) and the newest version of jasmine (3.3.0). The short term workaround is to lock your jasmine-core version to 3.2.0.

Cakephp 3 unit test unable to post data

I run an api using postman, it works. But my unit tests that I create for it doesn't work
Below is my unit test file
<?php
namespace App\Test\TestCase\Controller\Api;
use App\Controller\Api\EmployeesController;
use Cake\TestSuite\IntegrationTestCase;
/**
* App\Controller\Api\EmployeesController Test Case
*/
class EmployeesApiControllerTest extends IntegrationTestCase
{
/**
* Fixtures
*
* #var array
*/
public $fixtures = [
'app.projects',
'app.projects_sites',
'app.transactions',
'app.sites'
];
/**
* Test REST API PIN login
*/
public function testJwtToken() {
$this->configRequest([
'headers' => [
'Accept' => 'application/json',
'Content-Type' => 'application/json'
]
]);
$this->post('/api/employees/token', ['pin_code' => '1001']);
$this->assertResponseOk();
}
}
And this is the console response after running it
$ docker-compose run webapp vendor/bin/phpunit tests/TestCase/Controller/Api/EmployeesApiControllerTest.php
Starting timesheetcakephp_mysql_1 ... done
PHPUnit 6.5.7 by Sebastian Bergmann and contributors.
F 1 / 1 (100%)
Time: 1.52 seconds, Memory: 6.00MB
There was 1 failure:
1) App\Test\TestCase\Controller\Api\EmployeesApiControllerTest::testJwtToken
Status code is not between 200 and 204
Failed asserting that 500 is equal to 204 or is less than 204.
/var/www/html/vendor/cakephp/cakephp/src/TestSuite/IntegrationTestCase.php:796
/var/www/html/vendor/cakephp/cakephp/src/TestSuite/IntegrationTestCase.php:713
/var/www/html/tests/TestCase/Controller/Api/EmployeesApiControllerTest.php:37
FAILURES!
Tests: 1, Assertions: 4, Failures: 1.
The debug log keeps showing this
2018-03-29 19:47:13 Debug: duration=0 rows=0 SELECT Employees.id AS `Employees__id`, Employees.project_id AS `Employees__project_id`, Employees.name AS `Employees__name` FROM employees Employees WHERE Employees.pin_code = NULL LIMIT 1
I don't understand why the pin_code keep stating as NULL when I have clearly stated in my unit test to be '1001'.

Karma tests fail with Browser DISCONNECTED error, exit code: 1

We have a total of 2016 unit test cases written with Jasmine and are using Karma to run them. The tests run for a period of 1 min 30 sec to 2 min and then suddenly Karma disconnects from the browser.Here is a screenshot of the console logs.
The problem is that I am not able to diagnose why that is happening and which test case is causing it to get disconnected. I have tried different reporters of Karma to be able to identify the test case which forces it to disconnect from the browser but have been unsuccessful so far.
I have also tried running the tests in short batches to be able to drill down to the error test case (in case it is a test case error and not Karma configuration) but so far, the error has been thrown for all batches.
As per this post, I have tried setting the browserNoActivityTimeout to as high as 10 minutes (600000ms) but still no resolution. Also, the post mentions that there might be a problem with insufficient memory, so I have tried running the cases in one 8GB RAM and one 16GB RAM systems (Windows 10 on both).
Here's the complete stack trace:
[02:06:48] Error: MyApp Chromebook Unit tests failed with exitCode: 1
at formatError (C:\Users\barnadeep.bhowmik\AppData\Roaming\npm\node_modules\gulp\bin\gulp.js:169:10)
at Gulp.<anonymous> (C:\Users\barnadeep.bhowmik\AppData\Roaming\npm\node_modules\gulp\bin\gulp.js:195:15)
at emitOne (events.js:96:13)
at Gulp.emit (events.js:188:7)
at Gulp.Orchestrator._emitTaskDone (C:\Users\barnadeep.bhowmik\Desktop\Projects\MyProject\test-player-15-may\myapp-chrome\node_modules\orchestrator\index.js:264:8)
at C:\Users\barnadeep.bhowmik\Desktop\Projects\MyProject\test-player-15-may\myapp-chrome\node_modules\orchestrator\index.js:275:23
at finish (C:\Users\barnadeep.bhowmik\Desktop\Projects\MyProject\test-player-15-may\myapp-chrome\node_modules\orchestrator\lib\runTask.js:21:8)
at cb (C:\Users\barnadeep.bhowmik\Desktop\Projects\MyProject\test-player-15-may\myapp-chrome\node_modules\orchestrator\lib\runTask.js:29:3)
at C:\Users\barnadeep.bhowmik\Desktop\Projects\MyProject\test-player-15-may\myapp-chrome\build\tasks\test.js:18:13
at removeAllListeners (C:\Users\barnadeep.bhowmik\Desktop\Projects\MyProject\test-player-15-may\myapp-chrome\node_modules\karma\lib\server.js:336:7)
at Server.<anonymous> (C:\Users\barnadeep.bhowmik\Desktop\Projects\MyProject\test-player-15-may\myapp-chrome\node_modules\karma\lib\server.js:347:9)
at Server.g (events.js:291:16)
at emitNone (events.js:91:20)
at Server.emit (events.js:185:7)
at emitCloseNT (net.js:1555:8)
at _combinedTickCallback (internal/process/next_tick.js:71:11)
at process._tickCallback (internal/process/next_tick.js:98:9)
Here's my config file:
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
files: [
'bower_components/jquery/dist/jquery.js',
'node_modules/angular/angular.js',
'other_dependencies/**.*.js',
'src/app/app.js',
'src/app/pack1-components/**/*.js',
'src/app/pack2-components/**/*.js',
'src/**/*.html'
],
exclude: [
'src/some-folder/*',
],
port: 8081,
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: ['ChromeNoSandbox'],//temp fix for Chrome Browser 'Chrome'
customLaunchers: {
ChromeNoSandbox: {
base: 'Chrome',
flags: ['--no-sandbox']
}
},
reporters: ["spec","progress","coverage","html"],
specReporter: {
maxLogLines: 5, // limit number of lines logged per test
suppressErrorSummary: false, // do not print error summary
suppressFailed: false, // do not print information about failed tests
suppressPassed: false, // do not print information about passed tests
suppressSkipped: true, // do not print information about skipped tests
showSpecTiming: false, // print the time elapsed for each spec
failFast: true // test would finish with error when a first fail occurs.
},
preprocessors: {
'src/**/*.js':['coverage'],
'src/**/*.html':['ng-html2js']
},
coverageReporter: {
type: 'lcov',
dir: 'qualityreports/testresults/unit/coverage/'
},
htmlReporter: {
outputFile: 'qualityreports/testresults/unit/testresults.html'
},
browserNoActivityTimeout: 600000,
captureTimeout: 60000,
browserDisconnectTimeout : 60000,
browserDisconnectTolerance : 1,
ngHtml2JsPreprocessor: {
},
plugins: [
'karma-jasmine','karma-chrome-launcher','karma-coverage','karma-htmlfile-reporter','karma-ng-html2js-preprocessor',"karma-spec-reporter"],
singleRun: true
});
};
Here is a similar post but it did not have all details, hence posting mine. Any help would be deeply appreciated.

karma + jasmine unit tests show define is not defined

I am using Karma and jasmine to write my unit tests. I transpile ES6 code to ES5 to run the tests on but when ever I run the tests I get an error saying:
Chrome 51.0.2704 (Windows 10 0.0.0) ERROR
Uncaught ReferenceError: define is not defined
My karma.conf.js is this:
// Karma configuration
// Generated on Wed Jun 08 2016 07:12:07 GMT-0400 (Eastern Daylight Time)
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: ['jspm','jasmine'],
// list of files / patterns to load in the browser
files: [
{pattern: 'lib/**/*.min.js', included: false},
{pattern: 'js/Test/Dashboard/Unit/src/*.js', included: true},
{pattern: 'js/Test/Dashboard/Unit/src/**/*.js', included: true},
{pattern: 'js/Test/*Spec.js', included: true},
{pattern: 'js/Test/**/*Spec.js', included: true}
],
// list of files to exclude
exclude: [],
// 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: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['chrome_without_security'],
customLaunchers: {
chrome_without_security: {
base: 'Chrome',
flags: ['--disable-web-security']
}
},
// 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
})
}
The gulp task that runs the ES6-ES6 transpile is this:
gulp.task('build:aurelia', function(){
gulp.src([paths.dashboardPathJs, '!' + paths.dashboardJs])
.pipe(sourcemaps.init())
.pipe(babel({
presets: [ 'es2015-loose', 'stage-1'],
plugins: [
'syntax-flow',
'transform-decorators-legacy',
'transform-flow-strip-types',
'transform-es2015-modules-amd'
]
}))
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('./js/Test/Dashboard/Unit/src'));
});
I'm completely lost as to why I get the define is not defined error. Thank you in advance.

Using express with Karma to test ember app kit app

I've just downloaded and installed ember app kit. I've got it running and am using express to fake a backend by following the included directions.
I've also installed Karma and am attempting to run the tests with it in conjunction with the express backend. I don't believe the express app is being started though because when i view the output of Karma i see it attempting to perform a GET request and failing.
Failed to load resource: the server responded with a status of 404 (Not Found) http://1.10.1.10:9876/api/posts/1
Json is returned when i hit the development port(8000) though.
How do i tell Karma to start up the express app on port 9876 to test against?
I'm using the karma.conf.js from from the ember-app-kit-todos repo
Here is my Gruntfile.js. I also took bits from the todos repo:
module.exports = function(grunt) {
// To support Coffeescript, SASS, LESS and others, just install
// the appropriate grunt package and it will be automatically included
// in the build process:
//
// * for Coffeescript, run `npm install --save-dev grunt-contrib-coffee`
//
// * for SCSS (without SASS), run `npm install --save-dev grunt-sass`
// * for SCSS/SASS support (may be slower), run
// `npm install --save-dev grunt-contrib-sass`
// This depends on the ruby sass gem, which can be installed with
// `gem install sass`
// * for Compass, run `npm install --save-dev grunt-contrib-compass`
// This depends on the ruby compass gem, which can be installed with
// `gem install compass`
// You should not install SASS if you have installed Compass.
//
// * for LESS, run `npm install --save-dev grunt-contrib-less`
//
// * for Stylus/Nib, `npm install --save-dev grunt-contrib-stylus`
//
// * for Emblem, run the following commands:
// `npm uninstall --save-dev grunt-ember-templates`
// `npm install --save-dev grunt-emblem`
// `bower install emblem.js --save`
//
// * For EmberScript, run `npm install --save-dev grunt-ember-script`
//
// * for LiveReload, `npm install --save-dev connect-livereload`
//
// * for displaying the execution time of the grunt tasks,
// `npm install --save-dev time-grunt`
//
// * for minimizing the index.html at the end of the dist task
// `npm install --save-dev grunt-contrib-htmlmin`
//
// * for minimizing images in the dist task
// `npm install --save-dev grunt-contrib-imagemin`
//
// * for using images based CSS sprites (http://youtu.be/xD8DW6IQ6r0)
// `npm install --save-dev grunt-fancy-sprites`
// `bower install --save fancy-sprites-scss`
//
// * for automatically adding CSS vendor prefixes (autoprefixer)
// `npm install --save-dev grunt-autoprefixer`
//
var Helpers = require('./tasks/helpers'),
filterAvailable = Helpers.filterAvailableTasks,
_ = grunt.util._,
path = require('path');
Helpers.pkg = require("./package.json");
if (Helpers.isPackageAvailable("time-grunt")) {
require("time-grunt")(grunt);
}
// Loads task options from `tasks/options/` and `tasks/custom-options`
// and loads tasks defined in `package.json`
var config = _.extend({},
require('load-grunt-config')(grunt, {
configPath: path.join(__dirname, 'tasks/options'),
loadGruntTasks: false,
init: false
}),
require('load-grunt-config')(grunt, { // Custom options have precedence
configPath: path.join(__dirname, 'tasks/custom-options'),
init: false
})
);
grunt.loadTasks('tasks'); // Loads tasks in `tasks/` folder
config.env = process.env;
// App Kit's Main Tasks
// ====================
// Generate the production version
// ------------------
grunt.registerTask('dist', "Build a minified & production-ready version of your app.", [
'clean:dist',
'build:dist',
'copy:assemble',
'createDistVersion'
]);
// Default Task
// ------------------
grunt.registerTask('default', "Build (in debug mode) & test your application.", ['test']);
// Servers
// -------------------
grunt.registerTask('server', "Run your server in development mode, auto-rebuilding when files change.", function(proxyMethod) {
var expressServerTask = 'expressServer:debug';
if (proxyMethod) {
expressServerTask += ':' + proxyMethod;
}
grunt.task.run(['clean:debug',
'build:debug',
expressServerTask,
'watch'
]);
});
grunt.registerTask('server:dist', "Build and preview a minified & production-ready version of your app.", [
'dist',
'expressServer:dist:keepalive'
]);
// Testing
// -------
grunt.registerTask('test', "Run your apps's tests once. Uses Google Chrome by default.", [
'clean:debug', 'build:debug', 'karma:test' ]);
grunt.registerTask('test:ci', "Run your app's tests in PhantomJS. For use in continuous integration (i.e. Travis CI).", [
'clean:debug', 'build:debug', 'karma:ci' ]);
grunt.registerTask('test:browsers', "Run your app's tests in multiple browsers (see tasks/options/testem.js for configuration).", [
'clean:debug', 'build:debug', 'karma:browsers' ]);
grunt.registerTask('test:server', "Start a Karma test server and the standard development server.", function(proxyMethod) {
var expressServerTask = 'expressServer:debug';
if (proxyMethod) {
expressServerTask += ':' + proxyMethod;
}
grunt.task.run(['clean:debug',
'build:debug',
'karma:server',
expressServerTask,
'addKarmaToWatchTask',
'watch'
]);
});
// Worker tasks
// =================================
grunt.registerTask('build:dist', filterAvailable([
'createResultDirectory', // Create directoy beforehand, fixes race condition
'fancySprites:create',
'concurrent:buildDist', // Executed in parallel, see config below
]));
grunt.registerTask('build:debug', filterAvailable([
'jshint:tooling',
'createResultDirectory', // Create directoy beforehand, fixes race condition
'fancySprites:create',
'concurrent:buildDebug', // Executed in parallel, see config below
]));
grunt.registerTask('createDistVersion', filterAvailable([
'useminPrepare', // Configures concat, cssmin and uglify
'concat', // Combines css and javascript files
'cssmin', // Minifies css
'uglify', // Minifies javascript
'imagemin', // Optimizes image compression
// 'svgmin',
'copy:dist', // Copies files not covered by concat and imagemin
'rev', // Appends 8 char hash value to filenames
'usemin', // Replaces file references
'htmlmin:dist' // Removes comments and whitespace
]));
// Parallelize most of the build process
_.merge(config, {
concurrent: {
buildDist: [
"buildTemplates:dist",
"buildScripts",
"buildStyles",
"buildIndexHTML:dist"
],
buildDebug: [
"buildTemplates:debug",
"buildScripts",
"buildStyles",
"buildIndexHTML:debug"
]
}
});
// Templates
grunt.registerTask('buildTemplates:dist', filterAvailable([
'emblem:compile',
'emberTemplates:dist'
]));
grunt.registerTask('buildTemplates:debug', filterAvailable([
'emblem:compile',
'emberTemplates:debug'
]));
// Scripts
grunt.registerTask('buildScripts', filterAvailable([
'jshint:app',
'jshint:tests',
'coffee',
'emberscript',
'copy:javascriptToTmp',
'transpile',
'concat_sourcemap'
]));
// Styles
grunt.registerTask('buildStyles', filterAvailable([
'compass:compile',
'sass:compile',
'less:compile',
'stylus:compile',
'copy:cssToResult',
'autoprefixer:app'
]));
// Index HTML
grunt.registerTask('buildIndexHTML:dist', [
'preprocess:indexHTMLDistApp',
'preprocess:indexHTMLDistTests'
]);
grunt.registerTask('buildIndexHTML:debug', [
'preprocess:indexHTMLDebugApp',
'preprocess:indexHTMLDebugTests'
]);
// Appends `karma:server:run` to every watch target's tasks array
grunt.registerTask('addKarmaToWatchTask', function() {
_.forIn(grunt.config('watch'), function(config, key) {
if (key === 'options') { return; }
config.tasks.push('karma:server:run');
grunt.config('watch.' + key, config);
});
});
grunt.registerTask('createResultDirectory', function() {
grunt.file.mkdir('tmp/result');
});
grunt.initConfig(config);
};
I'm very new to EAK and Karma. Any help would be very much appreciated.
You can configure the location of the proxyURL in the package.json file, as seen here. You'll also need to make sure that the APIMethod is set to 'proxy' instead of 'stub'.
To actually have the server startup on a port other than 8000, you need to set an environment variable at the time you're running the tests. So, if you invoke grunt like this: PORT=9876 grunt test it should start the server on the port you specified.