I am trying to load some fixtures for testing purposes. So far I have prepared a json file.
I did set up my beforeEach function which should load particular file but I am getting an error:
Error: Fixture could not be loaded: tests/license_filter/license_test_data.json (status: error, message: undefined)
Part of test function:
beforeEach(function () {
jasmine.getFixtures().fixturesPath = 'tests/license_filter';
loadFixtures('license_test_data.json');
});
Karma config:
// Karma configuration
// Generated on Mon Nov 10 2014 21:12:33 GMT+0100 (Central European Standard Time)
module.exports = function (config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: 'license_tool/static',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'js/external/jquery.js',
'../../node_modules/jasmine-jquery/lib/jasmine-jquery.js',
'js/external/jquery.tmpl.js',
'js/external/jquery.validate.js',
'js/helpers.js',
'js/version_ninja.js',
'tests/**/*.html',
'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: {
'**/*.html': ['html2js']
},
// 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: ['PhantomJS'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
});
};
I've found a solution for that.
This is my beforeeach
beforeEach(function () {
jasmine.getJSONFixtures().fixturesPath = 'base/tests/license_filter';
loadJSONFixtures('license_test_data.json');
});
I had to add this to files list in karma.conf.js:
{
pattern: 'tests/**/*.json',
watched: true,
served: true,
included: false
}
Related
I am trying to test my directive with karma and webpack.
This is the karma config file
module.exports = function (config) {
config.set({
basePath: './',
frameworks: ["jasmine"],
files: [
{
pattern: 'directive.spec.ts',
watched: false
}],
exclude: [],
preprocessors: {
'directive.spec.ts': ['webpack', 'sourcemap']
},
webpackServer: {
noInfo: true
},
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: [
"PhantomJS"
],
singleRun: true,
reporters: ['mocha'],
webpack: {
resolve: {
extensions: ['', '.ts', '.js'],
modulesDirectories: ['node_modules', '.'],
},
module: {
loaders: [{
test: /\.ts$/,
loader: 'awesome-typescript-loader'
}]
},
stats: {
colors: true,
reasons: true
},
debug: true,
devtool: 'inline-source-map'
}
});
};
And the directive.spec.ts:
import { MyDirective } from './directive';
import {TestComponent} from './test';
import {
async,
inject,
TestBed,
} from '#angular/core/testing';
describe('TestComponent', () => {
let fixture: any;
beforeEach(() => {
fixture = TestBed.configureTestingModule({
declarations: [ TestComponent, MyDirective]
})
.createComponent(TestComponent);
fixture.detectChanges();
});
it('should work', () => {
expect(true).toBe(true);
});
But when I am trying to run my test I am getting this error:
PhantomJS 2.1.1 (Mac OS X 0.0.0) ERROR ReferenceError: Can't find
variable: Map at directive.spec.ts:1380
What am I missing here?
Please follow these steps. It worked for me:
1) Create a "karma-main.js" file with following code
require('core-js/es6');
require('core-js/es7/reflect');
require('zone.js/dist/zone');
require('zone.js/dist/long-stack-trace-zone');
require('zone.js/dist/proxy');
require('zone.js/dist/sync-test');
require('zone.js/dist/jasmine-patch');
require('zone.js/dist/async-test');
require('zone.js/dist/fake-async-test');
var appContext = require.context('<Source code root folder>', true, /\.spec\.ts/); // Assuming test case files ends with spec.ts
appContext.keys().forEach(appContext);
var testing = require('#angular/core/testing');
var browser = require('#angular/platform-browser-dynamic/testing');
testing.TestBed.initTestEnvironment(browser.BrowserDynamicTestingModule, browser.platformBrowserDynamicTesting());
2) Your karma.conf.js file should look like
var webpackConfig = require('./webpack.config')
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
plugins: [
'karma-jasmine',
'karma-PhantomJS-launcher',
'karma-webpack'
],
webpack: webpackConfig,
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
{ pattern: '<relative path to karma-main.js>', watched: false }
],
// 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: {
'<relative path to karma-main.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: ['PhantomJS'],
// 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
})
}
Here is my guess: somewhere in the code you use a class Map which appeared in ES6. But PhantomJS doesn't know about this class yet since it's something too new.
So there are 3 choices:
Get rid of usage of Map and use only current JS features (like Object properties) - the cleanest approach.
Use transpiler for transforming your ES6 code into ES5 that's well understood by modern browser. This has huge disadvantages as it will mess with your line numbers and you may have to sacrifice the possibility to debug some of the code.
Use polyfills that implement ES6 features as functions in external libraries (as Sachin Gaur suggested)
I'm trying for the first time to test my angular bundle create with browserify,
but when I run Karma, i have this error :
Chrome 50.0.2661 (Windows 10 0.0.0) it checks dataService objects, encountered a declaration exception FAILED
TypeError: module is not a function
at Suite.<anonymous> (C:/Users//1832d4dc6c0fa77886e1cae0916aaa85.browserify:811:13 <- testDrawer/testDataService.js:7:0)
at Object.require.C:\Users\\angularjs\testDrawer\testDataService.js (C:/Users//Temp/1832d4dc6c0fa77886e1cae0916aaa85.browserify:805:1 <- testDrawer/testDataService.js:1:0)
at s (C:/Users//AppData/Local/Temp/1832d4dc6c0fa77886e1cae0916aaa85.browserify:1:262 <- node_modules/browser-pack/_prelude.js:1:0)
at C:/Users//angularjs/testDrawer/testDataService.js:1:34
Chrome 50.0.2661 (Windows 10 0.0.0): Executed 1 of 2 (1 FAILED) (skipped 1) ERROR (0.026 secs / 0.003 secs)
Error comes from :
describe("it checks dataService objects,", function() {
it('it verifies installations');
var dataService;
beforeEach(module('drawerApp'));
beforeEach(inject(function (_dataService_) {
dataService = _dataService_;
}));
it('it verifies tool', function(){
expect(dataService.color.equals('black'));
});
});
My karma config :
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: ['browserify', 'jasmine'],
// list of files / patterns to load in the browser
files: [
'node_modules/angular/angular.js',
'node_modules/angular-mocks/angular-mocks.js',
'drawer/*.js',
'drawer/**/*.js',
'testDrawer/*.js'
],
// list of files to exclude
exclude: ['karma.conf.js' , 'drawer/drawerBundle.js' ],
browserify: {
debug: true
},
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'drawer/*.js' : ['browserify'],
'drawer/**/*.js': ['browserify'],
'testDrawer/*.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
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
})
`enter code here`};
The first test success but the second one failed beacause of :
beforeEach(module('drawerApp'));
Am I missing something?
we are developing a programm test-driven in Typescript.
This is our test with jasmine:
import IDifferentialPilotService = DifferentialPilot.IDifferentialPilotService;
import Ev3DifferentialPilotService = DifferentialPilot.Ev3DifferentialPilotService;
import IHttpService = ng.IHttpService;
describe("restClientService integration test: ", function () {
// sut
var ev3DifferentialPilotService: IDifferentialPilotService;
//doc
var http: IHttpService;
beforeAll(function () {
angular.mock.inject(function ($http: IHttpService) {
this.http = $http;
});
ev3DifferentialPilotService = new Ev3DifferentialPilotService(http);
});
it("robot should run 5 m", function () {
expect(ev3DifferentialPilotService.runDistance(5)).toBe("success");
});
});
the class Ev3DifferentialPilotService which is tested looks like that:
namespace DifferentialPilot {
"use strict";
import IHttpService = ng.IHttpService;
export class Ev3DifferentialPilotService implements IDifferentialPilotService {
private http: IHttpService;
static $inject = ['$http'];
constructor($http: IHttpService) {
this.http = $http;
}
public runDistance(runDistance: number): string {
this.http({
method: "POST",
url: "10.0.0.44:8080/differentpilot/run/5"
}).then(function successCallback(response: any) {
return "success";
}, function errorCallback(response: any) {
return "error";
});
return undefined;
}
}
}
Like you can see, we want to inject in our test the $http-service, so that Ev3DifferentialPilotService can retrieve the Http-service as parameter and use it in its runDistance-method.
When we log the this.$http-Object in Ev3DifferentialPilotService , then we get undefined, what means that the injection fails. According to that the test also fails.
Im registrating Ev3DifferentialPilotService as service in App.js:
var app = angular.module("AngularDifferentialPilotModule", []);
app.service("ev3DifferentialPilotService", DifferentialPilot.Ev3DifferentialPilotService);
And we using all that stuff in our karam.conf.js:
// Karma configuration
// Generated on Thu Dec 17 2015 14:02:38 GMT+0100 (Mitteleuropäische Zeit)
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: [
"bower_components/angular/angular.js",
"bower_components/angular-mocks/angular-mocks.js",
"src/Ev3DifferentialPilotService.js",
"spec/*.spec.js",
"src/app.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: false,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['Firefox'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,
// Concurrency level
// how many browser should be started simultanous
concurrency: Infinity
})
}
Furthermore we are using a tsconfig which looks like that:
{
"compilerOptions": {
"module": "commonjs",
"noImplicitAny": true,
"removeComments": true,
"preserveConstEnums": true,
"sourceMap": true
}
So where is the error? Can somebody help me?
You can't inject in beforeAll (https://github.com/angular/angular.js/issues/10238)
A feature has been opened (https://github.com/angular/angular.js/pull/14093) but not yet merged.
I am configuring my Karma amd mocha framework with grunt in my project. When I am running karma start I am getting below-mentioned error.
I am getting this error in my console while running command : Karma start
TypeError: expect(...).to.be is not a function
My Karma.confjs
// Karma configuration
// Generated on Fri Nov 27 2015 11:48:47 GMT+0530 (India 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: ['mocha', 'chai'],
// list of files / patterns to load in the browser
files: [
'bower_components/angular/angular.js',
'bower_components/angular-mocks/angular-mocks.js',
'app/*.js',
// 'test/specs/*.js',
'test/specs/array.js',
// 'test/specs/myCtlr-spec.js',
//'test/*.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','coverage'],
preprocessors: {
'src/app/**/*.js': ['coverage']
},
coverageReporter: {
type: 'lcov',
dir: '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: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
// browsers: ['PhantomJS', 'Chrome'],
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 simultanous
concurrency: Infinity
})
}
My array.js test
// var expect = require('chai').expect;
describe("Mocha: The 'toBe' matcher compares with ===", function() {
it("and has a positive case", function() {
expect(true).to.be(true);
});
it("and can have a negative case", function() {
expect(false).not.to.be(true);
});
});
Please suggest what I am missing.
You need to write expect(true).to.be.equal(true) the be is a chain (object) not a function. Or you could write:
expect(true).to.be.true;
expect(false).to.be.false;
My code depends on tons of other code, and is loaded last in the browser when running from the normal index.html-file. So of course when dependency 1 is jquery, and dependency 2 uses $.html(), and my code is loaded third, that works just fine in the browser.
But in Karma everything screeches to a halt since I'm loading 'jquery' from bower, not '$'.
To be clear: it's not my code that's creating errors, it's the dependencies. I don't get to test my code since everything errors out before then.
So how do I get the tests to work?
Note: I also run everything through webpack so I can use ES6-code, but webpack is loaded in Karma as well, so that should have no effect.
Chrome 45.0.2454 (Mac OS X 10.11.0) ERROR
Uncaught TypeError: Cannot set property '$' of undefined
at /Users/tom/dev/orm/bower_components/jointjs/dist/joint.js:37
Webpack.conf.js:
var webpack = require('webpack');
module.exports = {
devtool: 'source-map-loader',
externals: [
'jquery',
'joint',
'backbone',
'loadash'
],
// entry: './src/index.js',
// output: {
// path: './public',
// filename: 'designer.js'
// },
plugins: [
new webpack.ProvidePlugin({'$': 'jquery', 'jointjs': 'joint'})
],
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
}
]
}
};
Karma.conf.js:
// Karma configuration
// Generated on Thu Oct 08 2015 10:54:47 GMT+0200 (CEST)
var webconf = require('./webpack.config.js');
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',
'requirejs',
'bower'
],
// list of files / patterns to load in the browser
files: [
'test-main.js',
{
pattern: 'test/*.js',
included: false
}
],
bowerPackages: [
'jquery',
'jointjs',
'backbone',
'lodash'
],
// 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/*.js': [
'webpack',
'sourcemap'
],
'src/**/*.js': [
'webpack',
'sourcemap'
]
},
webpack: webconf,
// 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: [
'PhantomJS',
'Chrome'
],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
});
};
I think you're either looking for webpack externals
Webpack Externals
{
externals: {
// require("jquery") is external and available
// on the global var jQuery
"jquery": "jQuery"
}
}
...or, provide plugins.
Provide Plugin vs. Externals
plugins: [
new webpack.ProvidePlugin({
"_": "underscore"
})
]
Most likely provide plugin, because you want to provide that global variable to all the webpacked bundles.
I have no idea what changed, but it now works fine. I include here the final Karma config-file. The webpack-file is identical to the one above.
Note that a couple of configuration changes are actually just normal configuration changes that I've changed since getting it to work.
// Karma configuration
// Generated on Thu Oct 08 2015 10:54:47 GMT+0200 (CEST)
var webconf = require('./webpack.config.js');
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: [
'requirejs',
'bower',
'jasmine',
],
bowerPackages: [
'jquery',
'lodash',
'backbone',
'jointjs'
],
// list of files / patterns to load in the browser
files: [
'test-main.js',
{
pattern: 'test/*.js',
included: false
}
],
// 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/*.js': [
'webpack',
'sourcemap'
],
'src/**/*.js': [
'webpack',
'sourcemap'
]
},
webpack: webconf,
// 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,
client: {
captureConsole: false
},
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: [
'PhantomJS',
'Chrome'
],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
});
};