Can't use jasmine-jquery matchers - javascript

I am using Karma, Jasmine, and attempting to use some of the custom matchers jasmine-jquery provides to test some DOM manipulation I'm doing.
I have the following in my 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: ['jasmine-jquery', 'jasmine'],
files: [
'bower_components/angular/angular.js',
'bower_components/angular-mocks/angular-mocks.js',
'node_modules/jquery/dist/jquery.js',
'src/**/*',
'.tsout/*.js'
],
exclude: [
'**/*.ts',
'**/*.json'
],
preprocessors: {
'.tsout/*.js': 'coverage'
},
reporters: ['progress', 'coverage'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: ['Chrome'],
plugins: [
'karma-jasmine-jquery',
'karma-jasmine',
'karma-coverage'
],
singleRun: false
});
};
And, in one of my .spec.js files I have something like:
describe("DOM Stuffs", function(){
it("should have a DOM element with ID test", function(){
expect($('#test').toBeInDOM());
});
});
Karma fires off with no complaints, and all of my previous tests run as expected. When it gets to this test, however, I get the following TypeError:
TypeError: $(...).toBeInDOM is not a function at Object.<anonymous>
Any thoughts on what I'm missing here?
Versions: karma: 0.12.33 | jasmine: 2.1.1 | karma-jasmine: 0.3.5 | jasmine-jquery: 2.1.0 | karma-jasmine-jquery: 0.1.1

Related

How do I get 'npm test' to find my karma.conf.js file?

I have the following structure in my application:
Web (Asp net core)
|
|--wwwroot
|--ClientApp
| |--app
| | |-- ... (typescript modules, *.spec.js files etc.)
| |
| |--karma.config.js
| |--test-main.js
|
|--Controllers
|--config.json files for web etc.
In the console I'm in the ClientApp folder when running:
npm test
I get the following error:
File C:\Users\...\Web\karma.conf.js does not exist!
Why does it try to look for the karma.conf.js file in the Web folder?
How can I tell it to look in the right place? Even if I CD to the app folder I get the exact same error.
If I try to place the karma.conf.js file where it expects it, I get a bunch of other errors like:
cannot find module requirejs
I'm horribly confused, would really appreciate some help.
karma.conf.js file:
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine', 'requirejs'],
files: [
'test-main.js',
{pattern: 'test/**/*spec.js', included: false},
{pattern: '*.js', included: false}
],
exclude: [
],
preprocessors: {
},
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome', 'Firefox'],
singleRun: false,
concurrency: Infinity
})
}
test-main.js:
var allTestFiles = []
var TEST_REGEXP = /(spec|test)\.js$/i
Object.keys(window.__karma__.files).forEach(function (file) {
if (TEST_REGEXP.test(file)) {
var normalizedTestModule = file.replace(/^\/base\/|\.js$/g, '')
allTestFiles.push(normalizedTestModule)
}
})
require.config({
baseUrl: '/base',
deps: allTestFiles,
callback: window.__karma__.start
})
Just go into your package.json and edit the test script to point to the location of your karma config.
"scripts": {
"test": "karma start ./path/to/karma.conf.js"
}

Karma - How to point to a source map for typescript coverage

I like to generate a coverage report for my typescript source files with karma-coverage. My unit tests are written in javascript and I'm using the Jasmine Test framework.
My folder structure looks like this:
node_modules/
app/
app.js
app.js.map
app.ts
components/
controllers/
SampleController.ts
directives/
filters/
services/
unittests/
karma.conf.js
components/
controllers/
SampleControllerTest.js
directives/
filters/
services/
My karma.conf.js
module.exports = function(config) {
config.set({
frameworks: ['jasmine'],
plugins: [
'karma-jasmine',
'karma-ng-html2js-preprocessor',
'karma-coverage',
'karma-phantomjs-launcher',
'karma-sourcemap-loader'
],
preprocessors: {
'../app/directives/controls/**/*Template.html' : [ 'ng-html2js' ],
// source files, that you wanna generate coverage for
// do not include tests or libraries
// (these files will be instrumented by Istanbul)
'../app/app.js' : ['sourcemap', 'coverage' ],
},
reporters: ['progress', 'coverage'],
// web server port
port: 9876,
coverageReporter: {
type : 'html',
dir : 'coverage/'
},
// and some other stuff
});
};
Currently my coverage report delivers sufficient metrics but not related to the single typescript files but the app.js.
I suppose that I either messed up something with the preprocessor config or that I need to specify the source map.
Anny hints?
Using karma-istanbul-remap does the trick for me.
karma.conf.js:
module.exports = function(config) {
config.set({
frameworks: ['jasmine'],
plugins: [
'karma-jasmine',
'karma-ng-html2js-preprocessor',
'karma-coverage',
'karma-phantomjs-launcher',
'karma-remap-istanbul'
],
preprocessors: {
'../app/directives/controls/**/*Template.html' : [ 'ng-html2js' ],
// source files, that you wanna generate coverage for
// do not include tests or libraries
// (these files will be instrumented by Istanbul)
'../app/app.js' : ['coverage' ],
},
reporters: ['progress', 'coverage', 'karma-remap-istanbul'],
// web server port
port: 9876,
coverageReporter: {
type : 'json',
subdir : '.',
dir : 'coverage/',
file : 'coverage.json'
},
remapIstanbulReporter: {
src: 'coverage/coverage.json',
reports: {
lcovonly: 'coverage/lcov.info',
html: 'coverage/html/report'
},
timeoutNotCreated: 5000, // default value
timeoutNoMoreFiles: 1000 // default value
},
// and some other stuff
});
};

Unit Testing Browserify Project with Karma + Jasmine

I am trying to setup unit testing for a JavaScript plugin that is based on AngularJS. The plugin is bundled with Browserify via Gulp. It depends on external libraries that are injected with wiredep and gulp-inject from the bower_components folder. This is all working beautifully in the generated bundle, but if I try to run a Karma unit test via gulp, I get the following error:
Uncaught TypeError: angular.module is not a function at /tmp/94dbea5947f4758ab1ee6935e2f4b3f1.browserify:365 <- app/js/services/index.js:9:0
In this file, angular is loaded with var angular = require('angular');, and a console.log(angular) gives an empty object.
My karma.conf.js:
'use strict';
const istanbul = require('browserify-istanbul');
const isparta = require('isparta');
const mainBowerFiles = require('main-bower-files');
const karmaBaseConfig = {
basePath: '../',
frameworks: ['jasmine', 'browserify'],
preprocessors: {
'app/js/**/*.js': ['browserify', 'coverage'],
'**/*.html': ['ng-html2js']
},
browserify: {
debug: true,
extensions: ['.js'],
transform: [
[["babelify", {"ignore": "/\/bower_components\//"}]],
'browserify-ngannotate',
'bulkify',
'debowerify',
'brfs',
istanbul({
instrumenter: isparta,
ignore: ['**/bower_components/**', '**/node_modules/**', '**/test/**']
})
]
},
ngHtml2JsPreprocessor: {
stripPrefix: 'app/',
moduleName: 'templates'
},
plugins: [
'karma-jasmine',
'karma-coverage',
'karma-browserify',
'karma-ng-html2js-preprocessor',
'karma-chrome-launcher'
],
files: mainBowerFiles({
filter: '**/*.js',
paths: {
bowerDirectory: 'bower_components',
bowerrc: '.bowerrc',
bowerJson: 'bower.json'
}
}).concat([
// app-specific code
'app/js/main.js',
// 3rd-party resources
'node_modules/angular-mocks/angular-mocks.js',
// test files
'test/unit/**/*.js'
]),
exclude: [],
reporters: ['progress', 'coverage'],
port: 9876,
colors: true,
autoWatch: false,
browsers: ['Chrome'],
singleRun: true
};
const customLaunchers = {
chrome: {
base: 'SauceLabs',
browserName: 'chrome'
}
};
const ciAdditions = {
sauceLabs: {
testName: 'Karma Unit Tests',
startConnect: false,
build: process.env.TRAVIS_BUILD_NUMBER,
tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER
},
browsers: Object.keys(customLaunchers),
customLaunchers: customLaunchers,
reporters: ['progress', 'coverage', 'saucelabs']
};
module.exports = function (config) {
const isCI = process.env.CI;
config.set(isCI ? Object.assign(karmaBaseConfig, ciAdditions) : karmaBaseConfig);
};
All main application files are located under app/, bower files in bower_components/, node modules in node_modules/ and test specs in test/unit/.
It is based on this boilerplate: https://github.com/jakemmarsh/angularjs-gulp-browserify-boilerplate.
The error occurs just after Karma has launched Chrome, but before any unit test are executed (I checked with console.log in the unit test).
Any help would be greatly appreciated.
Finally solved it.
unit.js (gulp unit task):
'use strict';
import config from '../config';
import path from 'path';
import gulp from 'gulp';
import {Server} from 'karma';
gulp.task('unit', ['copy-bower-components',
'styles',
'images',
'fonts',
'api',
'views',
'browserify',
'inject'
], function (done) {
new Server({
configFile: path.resolve(__dirname, '../..', config.test.karma),
singleRun: true
}, function (exitCode) {
console.log('Karma has exited with ' + exitCode);
done();
}).start();
});
The key here was to run browserify before the unit tests are started. karma.conf.js:
// Karma configuration
// Generated on Sat Jan 23 2016 16:43:48 GMT+0100 (CET)
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', 'browserify'],
// list of files / patterns to load in the browser
files: [
"bower_components/tether/dist/js/tether.js",
"bower_components/jquery/jquery.js",
"bower_components/bootstrap/dist/js/bootstrap.js",
"bower_components/jquery-ui/jquery-ui.js",
"bower_components/rangy/rangy-core.js",
"bower_components/rangy/rangy-classapplier.js",
"bower_components/rangy/rangy-highlighter.js",
"bower_components/rangy/rangy-selectionsaverestore.js",
"bower_components/rangy/rangy-serializer.js",
"bower_components/rangy/rangy-textrange.js",
"bower_components/angular/angular.js",
"bower_components/textAngular/dist/textAngular.js",
"bower_components/textAngular/dist/textAngular-sanitize.js",
"bower_components/textAngular/dist/textAngularSetup.js",
"bower_components/KaTeX/dist/katex.min.js",
"bower_components/angular-bootstrap/ui-bootstrap-tpls.js",
"bower_components/angular-translate/angular-translate.js",
"bower_components/angular-translate-loader-static-files/angular-translate-loader-static-files.js",
"bower_components/angular-cookies/angular-cookies.js",
"bower_components/angular-translate-storage-cookie/angular-translate-storage-cookie.js",
"bower_components/angular-translate-storage-local/angular-translate-storage-local.js",
"bower_components/angular-translate-handler-log/angular-translate-handler-log.js",
"bower_components/angular-dynamic-locale/src/tmhDynamicLocale.js",
"bower_components/angular-tour/dist/angular-tour-tpls.min.js",
"bower_components/ng-sortable/dist/ng-sortable.js",
"bower_components/moment/moment.js",
"bower_components/angular-moment/angular-moment.js",
"bower_components/KaTeX/dist/contrib/auto-render.min.js",
'dist/js/main.js',
'node_modules/angular-mocks/angular-mocks.js',
'test/unit/**/*.spec.js'
],
browserify: {
debug: true,
transform: [
'babelify',
'brfs',
'bulkify'
]
},
// list of files to exclude
exclude: ['karma.conf.js'],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'test/unit/**/*.spec.js': ['browserify']
},
// 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'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,
urlRoot: '/__karma__/'
})
};

Jasmine Tests give error "Uncaught ReferenceError: require is not defined"

I am trying to run Jasmine tests with Karma on my React site. My tests were working before, and I'm not sure what has changed, but now I get the error:
Uncaught ReferenceError: require is not defined
for Chrome and PhantomJS and Firefox give me similar errors. Please let me know if more info would be helpful. I have found a lot of similar questions on the web, but nothing that fixes the problem.
You can see the test file below and the full project is on my github repo.
Thanks in advance!
My test file looks like this:
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');
});
});
My karma.conf.js file looks like this:
// 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'],
// list of files / patterns to load in the browser
files: [
'./node_modules/phantomjs-polyfill/bind-polyfill.js',
'test/karma_tests/*test.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'
],
// 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
});
};
This is the error I get after making the changes #guilhebl recommended:
Firefox 40.0.0 (Ubuntu 0.0.0) ERROR
Error: Module name "react/addons" 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
Here is the karma.conf.js after I made the changes:
// 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'],
// list of files / patterns to load in the browser
files: [
'./node_modules/phantomjs-polyfill/bind-polyfill.js',
'./node_modules/requirejs/require.js',
'./node_modules/karma-requirejs/lib/adapter.js',
'./test/karma_tests/*test.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
});
};
You should have require configured in your karma.conf file such as example:
module.exports = function(config){
config.set({
frameworks: ['jasmine'],
plugins : [
'karma-chrome-launcher',
'karma-firefox-launcher',
'karma-script-launcher',
'karma-phantomjs-launcher',
'karma-jasmine',
'karma-requirejs'
],
files : [
'node_modules/requirejs/require.js',
'node_modules/karma-requirejs/lib/adapter.js',
'app/js/test-main.js',
{pattern: 'app/lib/**/*.js', included: false},
{pattern: 'app/js/**/*.js', included: false},
{pattern: 'app/js/views/**/*Test.js', included: false}
],
browsers: ['PhantomJS']
});
};

getting 'require is not defined' when testing in angularjs with karma

I am using angulajs with browersify to build an app. To test it, I'd like to use Karma.
I jave set up my conf file like this:
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine', 'browserify'],
files: [
'node_modules/angular/angular.js',
'node_modules/angular-mocks/angular-mocks.js',
'src/app/*',
'src/app/*/*'
],
exclude: [
'src/app/*/*.jade'
],
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
browserify: {
debug: true
},
preprocessors: {'src/app/*/*.js': ['browserify']}
});
};
And my app.js file looks like this:
require('angular')
require('angular-mocks')
var uiRouter = require('angular-ui-router')
var serices = require('./services')
var directives = require('./directives')
var controllers = require('./controllers')
var routes = require('./routes')
angular.module('myApp', [uiRouter, 'ngMocks'])
// load Routes
.config(routes)
// Services
.service('someService', services.someService)
// Controllers
.controller('myCtrl', controllers.myCtrl)
// Directives
.directive('myDirective', directives.myDirective);
I am using karma-browserify but I still get the following error when running test:
'require is not defined'
How can I fix this?
You need to run browserify on your unit test files and include them in the files. I'm here including bundled.js, which is browserified app code.
This one is close to yours and it works.
(function() {
'use strict';
// 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: ['mocha', 'chai-as-promised', 'chai', 'browserify'],
// list of files / patterns to load in the browser
files: [
// app-specific code. This should be generated by gulp browserify. Includes Angular
'webapp/bundled.js',
// 3rd-party resources
'node_modules/angular-mocks/angular-mocks.js',
// test files
'unit/**/*.js'
],
// list of files to exclude
exclude: ['karma.conf.js', 'protractor-conf.js'],
// Browserify config
browserify: {
watch: true,
debug: true
},
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'unit/**/*.js': ['browserify']
},
// 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
// - IE
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari
// - PhantomJS
browsers: ['Chrome', 'IE', 'Firefox'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: true
});
};
})();

Categories

Resources