Im try to develop a react module with ES6 and couldn't find any generator for that, so i had to make it from a basic one. I was able to config almost everything, but im have a lot of problems try to configure karma, to test my module.
This is my karma.conf.js
// Karma configuration
// http://karma-runner.github.io/0.12/config/configuration-file.html
// Generated on 2015-03-17 using
// generator-karma 0.9.0
module.exports = function(config) {
'use strict';
config.set({
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// base path, that will be used to resolve files and exclude
basePath: '../',
// testing framework to use (jasmine/mocha/qunit/...)
frameworks: ['commonjs', 'mocha', 'chai'],
// list of files / patterns to load in the browser
files: [
'node_modules/karma-babel-preprocessor/node_modules/babel-core/browser-polyfill.js',
'node_modules/react/react.js',
'lib/**/*.js',
'test/**/*.js'
],
preprocessors: {
'lib/**/*.cjsx': ['cjsx'],
'test/**/*.cjsx': ['cjsx'],
'lib/**/*.js': ['babel', 'commonjs'],
'test/**/*.js': ['babel', 'commonjs']
},
babelPreprocessor: {
options: {
sourceMap: 'inline'
},
filename: function (file) {
return file.originalPath.replace(/\.js$/, '.es5.js');
},
sourceFileName: function (file) {
return file.originalPath;
}
},
// list of files / patterns to exclude
exclude: [
],
// web server port
port: 8080,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers: [
'Chrome', 'PhantomJS'
],
// Which plugins to enable
plugins: [
'karma-commonjs',
'karma-cjsx-preprocessor',
'karma-babel-preprocessor',
'karma-phantomjs-launcher',
'karma-chrome-launcher',
'karma-mocha',
'karma-chai'
],
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false,
colors: true,
// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel: config.LOG_INFO,
// Uncomment the following lines if you are using grunt's server to run the tests
// proxies: {
// '/': 'http://localhost:9000/'
// },
// URL root prevent conflicts with the site root
// urlRoot: '_karma_'
});
};
At this point i have the following error
Chrome 42.0.2311 (Mac OS X 10.10.2) ERROR
Uncaught ReferenceError: module is not defined
at /Users/admin/workspace/open_source/react-component-inspector/node_modules/react/react.js:1
and if i remove the react ref from files section i get this other error
PhantomJS 1.9.8 (Mac OS X) ERROR
Uncaught Error: Could not find module 'react' from '/Users/admin/workspace/open_source/react-component-inspector/lib/index.es5.js'
at /Users/admin/workspace/open_source/react-component-inspector/node_modules/karma-commonjs/client/commonjs_bridge.js:85
And if i remove the commonJS i get
PhantomJS 1.9.8 (Mac OS X) ERROR
ReferenceError: Can't find variable: exports
at /Users/admin/workspace/open_source/react-component-inspector/lib/index.es5.js:5
Or al least can anyone recommend me a yo generator with karma, ES6, jsx, to build a module, not a web app?
Thanks for the help
I believe you just need to add the react file's path to the list of preprocessor files. This is because the react file is also using the commonjs format just like your app's files, and when that file gets loaded in chrome, unlike node, the browser has no notion of where the "module" object came from. Updated excerpt from your code below.
// list of files / patterns to load in the browser
files: [
'node_modules/karma-babel-preprocessor/node_modules/babel-core/browser-polyfill.js',
'node_modules/react/react.js',
'lib/**/*.js',
'test/**/*.js'
],
preprocessors: {
// you can probably leave off babel here.
'node_modules/react/react.js': ['babel', 'commonjs'],
'lib/**/*.cjsx': ['cjsx'],
'test/**/*.cjsx': ['cjsx'],
'lib/**/*.js': ['babel', 'commonjs'],
'test/**/*.js': ['babel', 'commonjs']
},
Related
I'm using Angular 4, Webpack 2.4.1, Karma 1.6 and Jasmine 2.6.1 and am writing ES2015 not TypeScript
I've got a tiny angular demo app and I want to add unit tests. The demo app itself itself is working and Webpack is bundling everything correctly, but when I try to run the unit tests I see some errors in the console like this:
ReferenceError: Can't find variable: Map
at Static/js/app.welcome.js:2569
(app.welcome.js is the name of my component)
Webpack appears to be building my test bundle properly, Karma server is starting up correctly and PhantomJS is launching correctly, but then I see several of the Map errors.
I'm definitely not using the Map() constructor in my own code.
Here are my files -
app.welcome.js:
import {Component} from '#angular/core';
class WelcomeComponent {
constructor () {
this.welcomeMessage = 'Welcome to Angular 4';
}
}
WelcomeComponent.annotations = [
new Component({
selector: 'my-app',
template: '<h1>{{welcomeMessage}}</h1>'
})
];
export {WelcomeComponent};
app.welcome.spec.js:
import {TestBed} from '#angular/core/testing';
import {WelcomeComponent} from '../../js/app.welcome';
describe('The Welcome component', function () {
let component;
beforeEach(function() {
TestBed.configureTestingModule({
declarations: [WelcomeComponent]
});
const fixture = TestBed.createComponent(WelcomeComponent);
component = fixture.componentInstance;
});
it('should be a component', function() {
expect(component).toBeDefined();
});
it('should have a welcome message', function () {
expect(component.welcomeMessage).toEqual('Welcome to Angular 4');
});
});
karma.conf.js:
const webpack = require('webpack');
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
files: [
'./Static/js/**/*.js',
'./Static/test/**/*.spec.js'
],
exclude: [
'./Static/js/main.js'
],
preprocessors: {
'./Static/js/**/*.js': ['webpack'],
'./Static/test/**/*.spec.js': ['webpack']
},
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: ['PhantomJS'],
singleRun: true,
concurrency: Infinity,
webpack: {
module: {
rules: [{
test: /\.js$/,
use: [{
loader: 'babel-loader',
options: { presets: ['es2015'] }
}]
}]
},
plugins: [
new webpack.ContextReplacementPlugin(/angular(\\|\/)core(\\|\/)#angular/, './src')
]
}
})
}
I've tried adding imports to my test file like import 'zone.js'; and import 'core-js/es6'; after reading other answers here, but this has not helped.
I've looked through Testing -ts - GUIDE and I don't appear to be missing anything huge from the earlier basic examples, but the problem is that all the official docs are geared towards TypeScript, while I want to use ES2015.
I understand that Map is an new type of object in ES2015 and not a variable as indicated by the error. Shouldn't Babel support this though?
Can anyone help?
This error is thrown because there's no Map in browsers. PhantomJS is used as Karma driver, and it doesn't support ES6 features.
If polyfills (e.g. core-js) aren't loaded in files that were included in tests, they should be loaded separately, for example via karma-es6-shim plugin:
...
frameworks: ['es6-shim', 'jasmine'],
...
This is what has worked for me:
I was using PhantonJs with karma and nightwatch for my testing . I was getting this error during JhantomJs initialization and as test were getting started because because there's no Map in browsers. PhantomJS is used as Karma driver, and it doesn't support ES6 features.
I tried to load polyfills but that did not help as well.
Then I saw that support for PhantonJs has long gone and felt it wont work. So I took an effort to replace PhantomJs with Chrome headless browser and surprisingly it was pretty easy to replace.
Here are the thing I did to make the change from PhantomJs to Chrome headless:
Package.json - puppeteer, chromedriver, karma-chrome-launcher as dependency
Add the following in karma.conf.js
const puppeteer = require('puppeteer');
process.env.CHROME_BIN = puppeteer.executablePath();
module.exports = function(config) {
config.set({
.
browsers: ['ChromeHeadless'],
.
});
Add/Edit the following in nightwatch.json
"chrome": {
"desiredCapabilities": {
"browserName": "chrome",
"javascriptEnabled": true,
"acceptSslCerts": true,
"chromeOptions": {
"args": ["--no-sandbox", "headless"]
}
}
This is something which has worked for me; may or may not work for you depending on the kind of side things you are using with JhantomJs for testing. Nevertheless should helpful for anyone who is trying to move away PhantomJs.
I'm new to Jasmine/Karma unit testing for JavaScript applications. I'm trying to implement it in my current project which is using Angular 1.4.12 and Webpack 1.13.1 for bundling. My folder structure is as follows:
The index.js file inside 'core' is trying to require various other modules which are required for Webpack bundling. The file looks like this:
require('../../bower_components/font-awesome/css/font-awesome.min.css');
require('../../bower_components/bootstrap/dist/css/bootstrap.min.css');
require('./scripts/app');
require('./scripts/index');
require('./views/index');
require('./styles/index');
Now, when I'm trying to run a sample test file which resides at the following location: 'modules/st/scripts/controllers/st.test.js', I get the following error message:
Uncaught Error: Module name
"../../bower_components/font-awesome/css/font-awesome.min.css" has not
been loaded yet for context: _. Use require([])
http://requirejs.org/docs/errors.html#notloaded at
C:/gitcode/repo/fm-dashboard/node_modules/requirejs/require.js:143
My karma.conf.js file looks like:
var webpack = require('webpack');
var getWebpackConfig = require('./webpack.config.js');
var webpackConfig = getWebpackConfig('test');
webpackConfig.output.path = __dirname+'/_build/test';
webpackConfig.entry = {};
// Karma configuration
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'./node_modules/requirejs/require.js',
'./app/core/index.js',
'./bower_components/angular/angular.js',
'./bower_components/angular-mocks/angular-mocks.js'
],
// 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: {
'../app/core/index.js': ['webpack']
},
// 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: true,
// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity,
webpack: webpackConfig,
webpackMiddleware: {
noInfo: true
}
})
}
I was under the impression that including Webpack in the preprocessors object would resolve this require issue but seems like this is not the case.
I tried including 'commonjs' in my preprocessors object and frameworks array as suggested by a few people but it didn't help. Can anyone please let me know how to get rid of this 'require' issue and move ahead with my testing?
Thanks in advance.
I have a web app that's written in Coffeescript and that I'm testing with Karma. My tests are written and I'm now writing code to make the tests pass.
At the moment, every time I change my code, I need to rerun my tests manually by typing grunt karma in a terminal. Is there a way to set up karma to automatically rerun my tests whenever my .coffee files change?
Here's my karma.conf.js:
// Karma configuration
// http://karma-runner.github.io/0.10/config/configuration-file.html
module.exports = function(config) {
config.set({
// base path, that will be used to resolve files and exclude
basePath: '',
preprocessors: {
'**/*.coffee': ['coffee']
},
coffeePreprocessor: {
// options passed to the coffee compiler
options: {
bare: true,
sourceMap: false
},
// transforming the filenames
transformPath: function(path) {
return path.replace(/\.coffee$/, '.js')
}
},
// testing framework to use (jasmine/mocha/qunit/...)
frameworks: ['jasmine'], //,'requirejs'],
// list of files / patterns to load in the browser
files: [
'app/bower_components/**/*.js',
'app/scripts/*.js',
'app/scripts/**/*.js',
'test/spec/**/*.coffee',
'.tmp/scripts/**/*.js'
],
// list of files / patterns to exclude
exclude: [],
// web server port
port: 8080,
// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true, // change by davebenson. was false
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers: ['Chrome'],
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false
});
};
First of all, I know this question has been asked other times, but it seems to be different.
This is my karma config file:
// Karma configuration
// Generated on Thu Jan 21 2016 09:58:23 GMT-0300 (Argentina Standard 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: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'src/*.js',
'test/*.js',
'src/*.js',
'tests/*.js'
],
// 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 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
})
}
This is my test so far in order to make it work:
require('../src/person.js');
describe('Person ', function(){
it('Should say hi with proposed first name and last name', function() {
var person = new person();
expect(true).toEqual(true);
});
});
When I run karma I'm getting the error saying require is not defined.
How ever, karma-requirejs is installed globally by npm.
I was reading this question that seems to be the same problem:
Jasmine Tests give error "Uncaught ReferenceError: require is not defined"
But after adding
plugins : [
'karma-requirejs',
],
to the karma conf file, I have a lot of other errors, that seems it does not recognize this attibute?
How can I fix the error?
I suggest installing karma-requirejs in your project's root, or where all of your other npm modules live local to the project.
I am new to testing in angular.
There are no errors on running karma here .
expected(true).toBe(true) and expected(false).toBe(true) give the same output as below, i have no idea why.
karma start test/karma.conf.js
INFO [karma]: Karma v0.12.16 server started at http://localhost:9876/
INFO [launcher]: Starting browser Chrome
INFO [Chrome 34.0.1847 (Mac OS X 10.9.2)]: Connected on socket VDytVxMpXMxN0QTPU_kg with id 83112246
Chrome 34.0.1847 (Mac OS X 10.9.2): Executed 0 of 0 ERROR (0.022 secs / 0 secs)
karma.conf.js
// Karma configuration
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '..',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
//'app/*/*.js'
'app/bower_components/angular/angular.js',
'app/bower_components/jquery/jquery.js',
'app/bower_components/underscore/underscore-min.js',
'app/bower_components/jquery.cookie/jquery.cookie.js',
'app/bower_components/restangular/dist/restangular.min.js',
'app/bower_components/angular-resource/angular-resource.min.js',
'app/bower_components/angular-route/angular-route.min.js',
'app/bower_components/angular-route-segment/build/angular-route-segment.min.js',
'app/bower_components/angular-cookies/angular-cookies.js',
'app/bower_components/angular-sanitize/angular-sanitize.js',
'app/bower_components/angular-scenario/angular-scenario.js',
'app/bower_components/angular-mocks/angular-mocks.js',
'app/scripts/lib/ui-bootstrap-custom-0.10.0.min.js',
'app/scripts/lib/jquery-ui-1.10.3.custom.js',
'app/scripts/app.js',
'app/scripts/config/*.js',
'app/scripts/controllers/*.js',
'app/scripts/directives/*.js',
'app/scripts/services/*.js',
'app/scripts/filters/*.js',
'test/spec/controllers/main.js'
],
// 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 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
});
};
test/spec/controllers/main.js
'use strict';
describe('Controller: MainCtrl', function () {
it('should attach a list of awesomeThings to the scope', function () {
expect(true).toBe(false);
});
});
Put your karma.conf.js in the apps root directory and then just run karma start.
From the command you're running, it looks like the config file is in the test directory, but you've specified that the spec file is in test/spec/controllers. I'm guessing that's a mistake.