I'm using Grunt to run Jasmine unit tests with Phantom.
Grunfile.js
module.exports = function (grunt)
{
"use strict";
grunt.loadNpmTasks('grunt-browserify');
grunt.loadNpmTasks('grunt-karma');
grunt.initConfig(
{
pkg: grunt.file.readJSON('package.json'),
browserify: {
dev: {
files: {
'test-output.js':['src/methods.js']
},
options: {
browserifyOptions: {
debug: true
}
}
}
},
karma:
{
unit:{
configFile:"karma.conf.js"
}
}
});
};
with this Karma config file
module.exports = function(config)
{
config.set({
basePath: '',
frameworks: ['browserify', 'jasmine'],
files: [
'myDir/*.js'
],
exclude: [
],
preprocessors: {
'myDir/*.js':['browserify','reactify']
},
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: ['PhantomJS'],
browserify: {
debug: true,
transform: []
},
plugins: [
'karma-phantomjs-launcher',
'karma-jasmine','karma-bro'],
singleRun: true
});
};
React is installed locally as a package in the node_modules folder. I can grunt browserify and everything gets bundled into test-ouput.js as expected, but when I do grunt karma I get the error:
TypeError: 'undefined' is not a function (evaluating 'ReactElementValidator.createElement.bind
If I inspect the test-ouput.js file I can see that the ReactElementValidator.createElement.bind function is inside of the bundle. Any ideas what could be causing this?
This a know issue with phantomJS < 2.0. To fix this simply install phantomjs polyfill like this:
npm install --save-dev phantomjs-polyfill
And add it to the config like this.
files: [
'node_modules/phantomjs-polyfill/bind-polyfill.js',
'myDir/*.js'
]
I hope this helped.
Related
When I run karma, I'm getting the following warning:
WARNING in configuration
The 'mode' option has not been set, webpack will fallback to 'production' for this value. Set 'mode' option to 'development' or 'production' to enable defaults for each environment.
You can also set it to 'none' to disable any default behavior. Learn more: https://webpack.js.org/concepts/mode/
I tried adding mode: 'development' to my webpack-test.config.js file as suggested in the link above, but not only did that fail to make any difference, Intellij IDEA complained:
webpack: Property 'mode' is not allowed
My unit testing does run anyway, but I'd like to get rid of this warning. Any help is much appreciated.
Here's my webpack-test.config.js file:
const path = require('path');
const webpack = require('webpack');
const ROOT = path.resolve( __dirname, 'src' );
module.exports = {
mode: 'production',
context: ROOT,
resolve: {
extensions: ['.ts', '.js'],
modules: [
ROOT,
'node_modules'
]
},
module: {
rules: [
// PRE-LOADERS
{
enforce: 'pre',
test: /\.js$/,
use: 'source-map-loader'
},
// LOADERS
{
test: /\.ts$/,
exclude: [ /node_modules/ ],
use: 'ts-loader'
}
]
},
devtool: 'cheap-module-source-map',
devServer: {}
};
My karma.conf.js:
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('karma-webpack')
],
client:{
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
reports: [ 'html', 'lcovonly' ],
fixWebpackSourcePaths: true
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
files: [
'spec.bundle.js'
],
preprocessors: {
'spec.bundle.js': ['webpack']
},
webpack: require('./webpack-test.config')
});
};
And spec.bundle.js:
const testsContext = require.context("./", true, /\.spec\.ts$/);
testsContext.keys().forEach(testsContext);
I'm launching karma via:
karma start ./karma.conf.js
I stumbled on this by trial and error, replacing:
webpack: require('./webpack-test.config')
...in karma.conf.js with:
webpack: {
mode: 'development'
}
...and the warning is gone. Not only that, I discovered that I really didn't need my webpack-test.config, nor the two npm modules I'd loaded to support it, source-map-loader and ts-loader.
If someone really did want to both specify mode: 'development' and specify a particular webpack config file, I'm not sure how they'd do it. I experimented with a few options and couldn't find anything that would work. This stuff doesn't have great documentation :(
You shouldn't have to require the webpack package in your config file. Not sure if that is causing Intellij to get confused or not, but mode is certainly a valid property of webpack.
https://webpack.js.org/concepts/mode/
I also noticed that in your karma.conf.js file, the line webpack: require('./webpack-test.config') is missing the .js extension for the config file. That may be why your config settings are not reflected in your karma test.
I'm trying for a week run karma in a project. I've follow this tutorial AngularJS Unit Test but when run karma start the console shows this error:
PhantomJS 2.1.1 (Linux 0.0.0) ERROR
ReferenceError: Can't find variable: angular
at /home/user/workspace/UnitTest/app/app.js:1
I thought the problem was in my project, so i've created a new one and the error persists.
My karma.conf.js is
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
files: [
'app/*.js',
'tests/*.js',
'node_modules/angular/angular.js',
'node_modules/angular/angular.min.js',
'node_modules/angular-mocks/angular-mocks.js'
],
exclude: [
],
preprocessors: {
},
reporters: ['progress'],
// web server port
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['PhantomJS'],
customLaunchers: {
Chrome_without_security: {
base: 'PhantomJS',
flags: ['--disable-web-security']
}
},
singleRun: false,
concurrency: Infinity
})
}
and app.js
angular.module('MyApp', [])
.filter('reverse',[function(){
return function(string){
return string.split('').reverse().join('');
}
}])
I've tried to change the node version too, but it isn't worked.
The solution was put the angular imports before the app files like this:
files: [
'node_modules/angular/angular.js',
'node_modules/angular/angular.min.js',
'node_modules/angular-mocks/angular-mocks.js',
'app/*.js',
'tests/*.js'
]
What I am trying to achieve is running browserSync with grunt while using Visual studio code editor with the IIS Express Extension installed.
I can ran both IIS (Viusal Studio code extension) and browserSync using proxy:
Gruntfile.js
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
sass: {
dist: {
options: {
outputStyle: 'expanded',
sourceMap: true,
sourceMapEmbed: true
},
files: {
'scss/global.css': 'scss/mccann-global.scss',
'scss/_imports/theme/dark-theme.css': 'scss/_imports/theme/dark-theme.scss',
'scss/_imports/theme/light-theme.css': 'scss/_imports/theme/light-theme.scss',
}
}
},
watch: {
grunt: {
options: {
reload: true
},
files: ['Gruntfile.js']
},
sass: {
files: 'scss/**/*.scss',
tasks: ['sass']
}
},
browserSync: {
dev: {
bsFiles: {
src: [
'scss/*.css',
'index.aspx'
]
},
options:
{
proxy: 'localhost:49798', //our IIS server
port: 3000, // our new port
open: true,
watchTask: true
}
}
}
});
grunt.loadNpmTasks('grunt-browser-sync');
grunt.loadNpmTasks('grunt-sass');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-grunticon');
grunt.loadNpmTasks('grunt-exec');
grunt.registerTask('build', ['sass']);
grunt.registerTask('default', ['build','browserSync','watch']);
}
Grunt looks good:
Then:
Installed the google chrome COORS plugin and the server run just fine trough the login page... but once I hit the homepage I got two errors: 401 Unauthorized.
I was looking into this:Request format is unrecognized for URL unexpectedly ending in but didn't work for me.
I am trying to unit test (with Karma + Jasmine + karma-typescript) my TypeScript project. The project structure is as follows:
root
|- src/*.ts //all TypeScript source files
|- tests/unit/*.spec.ts //all spec (test) files
|- karma.conf.js
|- tsconfig.json
My karma.conf.js looks like following:
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', "karma-typescript"],
karmaTypescriptConfig: {
tsconfig: "./tsconfig.json"
},
files: [
'src/*.ts',
'tests/**/*Spec.ts'
],
exclude: [],
preprocessors: {
"**/*.ts": ["karma-typescript"]
},
reporters: ["progress", "karma-typescript"],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
concurrency: Infinity
})
}
My spec file looks like below:
import 'aurelia-polyfills'; //<- importing this, as the project have dependency on Aurelia
// import "babel-polyfill";
import "reflect-metadata";
import "jasmine";
import { Utility } from './../../src/Utility';
describe("this is a try to set up karma-jasmine-webpack test (TS)", () => {
it("utility_test", () => {
const result = Utility.doSomething();
const expected = Expected_Result;
expect(result).toEqual(expected);
});
});
But when I run karma start, I get
Chrome 55.0.2883 (Windows 10 0.0.0) ERROR
Uncaught TypeError: Reflect.getOwnMetadata is not a function
at C:/Users/spal/AppData/Local/Temp/karma-typescript-bundle-16376WqjdFvsYtjdI.js:2325
I assume, that it is because of pollyfill(s) is/are not being loaded in the browser. However, I have imported aurelia-pollyfills in my spec file.
Please suggest how this can be corrected.
Update: Anyone looking at this for answer, might also face issues with source map (Error: Could not find source map for:'') from karma-remap-istanbul trying to generate coverage report.
One way to avoid this problem is to simply remove the problematic reporter plugin. For example, change reporters: ['mocha', 'coverage', 'karma-remap-istanbul'] to reporters: ['mocha', 'coverage'].
Other solution would be to generate the source maps. In case you can't specify the same in your tsconfig.json, you can specify that in karma.conf.js if you are using karma-typescript:
karmaTypescriptConfig: {
tsconfig: "./tsconfig.json",
compilerOptions: {
sourceMap: true
}
}
Lastly, I ended up with reporters: ["mocha", "karma-typescript"], as it shows which test passed, and which failed, as well as generate a coverage report.
You are probably missing the reflect-metadata import:
$ npm install --save-dev reflect-metadata
Then add the following to your files:
files: [
{ pattern: "node_modules/reflect-metadata/Reflect.js", include: true },
{ pattern: "src/*.ts", include: true },
{ pattern: "tests/**/*Spec.ts", include: true }
]
I'm using Karma + Mocha to run my unit tests, everything works pretty well except whenever the tests fails,
When I run a test like
expect(player).to.be.an('object');
and it fails I would expect it to say that "Object was expected but string given" or something like that, Instead all I get is (for every single failed test, no matter how it fails, even when I try to asset true with false):
SyntaxError: Unexpected token N
at Object.parse (native)
at Array.map (native)
I know for a fact that there's no syntax errors in my code, so Im guessing that's something to do with karma/mocha and the way they handle the failed tests.. I just dont know where to look.. here is my gulp task:
var karmaServer = require('karma').server;
gulp.task('test', function (done) {
gutil.log('preparing tests.');
var runOnlyOnce = true;
// check if a parameter named "watch" is passed. if so - run tests in watch mode.
if (argv.watch){
runOnlyOnce = false;
}
if (runOnlyOnce){
gutil.log('Running only once.\nTo run in "watch" mode try: gulp test --watch');
} else {
gutil.log('Running in watch mode. Oh yeah.');
}
karmaServer.start({
configFile: __dirname +'/karma.conf.js',
singleRun: runOnlyOnce
}, function(exitCode) {
gutil.log('Karma has exited with ' + exitCode);
if (exitCode != 0){
gutil.log(gutil.colors.bgRed("Test(s) failed."));
}
process.exit(exitCode);
});
});
Here is my karma.conf file:
module.exports = function (config) {
'use strict';
config.set({
basePath: '',
frameworks: ['browserify', 'mocha', 'source-map-support'],
// reporters configuration
reporters: ['mocha'],
preprocessors: {
'test/**/*.spec.js': ['browserify']
},
files: [
{pattern: 'app/**/*.js', watched: true, included: false, served: false}, // watch these files, but dont bundle them for tests
'test/**/*.spec.js'
],
browserify: {
debug: true,
transform: ['babelify']
},
plugins: [
'karma-mocha-reporter',
'karma-mocha',
'karma-phantomjs-launcher',
'karma-chrome-launcher',
'karma-browserify',
'babel-plugin-espower',
'karma-ie-launcher',
'karma-source-map-support'
],
port: 9876,
colors: true,
usePolling: true,
atomic_save: false,
autoWatch : 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,
browsers: ["Chrome"] //, "IE", 'PhantomJS'
});
};
Any help would be much appreciated!!! Thank you!
So I found the problem, all I did was to remove the debug flag from the karma.conf file..
instead of
browserify: {
debug: true,
transform: ['babelify']
},
I did:
browserify: {
debug: false,
transform: ['babelify']
},
that did the trick.
I hope this helps anyone! cheers!