I've seen this question posted but can't seem to resolve the error. I'm trying to use jquery-jasmine to return some fake data and I'm unable to get past the 404 error when trying to load the json file. I'm using yeoman to scaffold my angular-gulp project. Is it not a good idea to put the json file in the module, along side the spec file? Where does karma run from, is this where I should be putting the json file? I tried using an absolute path for jasmine.getJSONFixtures().fixturesPath but still get an error. I added 'base' to the path of the fixture because I saw this fixed the error in another post but it didn't work for me. Any ideas?
WARN [web-server]: 404: /base/src/app/home/home.fixture.json?_=1445293824062
PhantomJS 1.9.8 (Mac OS X) homeController should have some resultsets FAILED
Error: JSONFixture could not be loaded: base/src/app/home/home.fixture.json (status: error, message: undefined)
undefined
project/
src/
app/home
home.controller.spec.js
home.fixture.json
...
gulp/unit-test.js
karma.conf.js
...
karma.conf.js:
'use strict';
module.exports = function(config) {
config.set({
basePath: '../',
autoWatch : true,
frameworks : ['jasmine'],
browsers : ['PhantomJS'],
plugins : [
'karma-phantomjs-launcher',
'karma-chrome-launcher',
'karma-firefox-launcher',
'karma-safari-launcher',
'karma-jasmine'
],
exclude : [
],
files : [
// fixtures
{
pattern: 'src/**/*.fixture.json',
watched: true,
served: true,
included: false
}
]
});
};
home.controller.spec.js
'use strict';
describe('homeController', function(){
beforeEach(function() {
module('homeModule');
var $httpBackend, scope, homeController, storageFactory;
module(function($provide) {
$provide.service('storageFactory', storageFactory);
});
inject(function($rootScope, $controller, $injector) {
$httpBackend = $injector.get('$httpBackend');
jasmine.getJSONFixtures().fixturesPath = 'base/src/app/home';
$httpBackend.whenGET('http://localhost:3000/my/api/home').respond(
getJSONFixture('home.fixture.json')
);
scope = $rootScope.$new();
homeController = $controller('homeController', {
$scope: scope
});
storageFactory = $injector.get('storageFactory');
});
});
it('should have some resultsets', function() {
$httpBackend.flush();
expect(scope.result_sets.length).toBe(59);
});
});
I had the same setup with yeoman-Angularjs-gulp and jquery-jasmine with the same 404 problem.
I solved it in 2 way,
The basePath was not setup in my karma config.
The path of the json file were not initially loaded by karma so they never got found.
So I added the line in the file loading:
{pattern: path.join(conf.paths.src, '/mockjson/*.json'),
watched: false,
included: false,
served: true}
This is the basic karma config that was built by yeoman with the 2 extra line:
var path = require('path');
var conf = require('./gulp/conf');
var _ = require('lodash');
var wiredep = require('wiredep');
function listFiles() {
var wiredepOptions = _.extend({}, conf.wiredep, {
dependencies: true,
devDependencies: true
});
return wiredep(wiredepOptions).js
.concat([
path.join(conf.paths.src, '/app/**/*.module.js'),
path.join(conf.paths.src, '/app/**/*.js'),
path.join(conf.paths.src, '/**/*.spec.js'),
path.join(conf.paths.src, '/**/*.mock.js'),
path.join(conf.paths.src, '/**/*.html'),
{pattern: path.join(conf.paths.src, '/mockjson/*.json'), watched: false, included: false, served: true}
]);
}
module.exports = function (config) {
var configuration = {
files: listFiles(),
singleRun: true,
autoWatch: false,
basePath: '',
frameworks: ['jasmine', 'angular-filesort'],
angularFilesort: {
whitelist: [path.join(conf.paths.src, '/**/!(*.html|*.spec|*.mock).js')]
},
ngHtml2JsPreprocessor: {
stripPrefix: 'src/',
moduleName: 'pagesBehindCouch'
},
browsers: ['PhantomJS'],
plugins: [
'karma-phantomjs-launcher',
'karma-angular-filesort',
'karma-jasmine',
'karma-ng-html2js-preprocessor'
],
preprocessors: {
'src/**/*.html': ['ng-html2js']
}
};
config.set(configuration);
};
I think the pattern: 'src/**/*.fixture.json', might be not at the src location you think it is.
Exemple that really helped me: Gunnar Hillert's Blog
In my case, I was loading an environment-configuration.json file in order to bootstrap the AngularJS application.
So, I also had to specify the proxy settings.
proxies: {
'/mockjson/': '/base/src/mockjson/',
}
Related
I'm trying to test a controller on an AngularJS app that injects $mdDialog as a dependency. I need to mock out the dialog but can't even get that far because the injection is not being recognized.
Here is the test file:
describe('responsesController', function() {
beforeEach(module('respondent.projects.project.responses'));
let responsesController, $rootScope, _$mdDialog_;
beforeEach(inject(function(_$controller_, _$rootScope_, _$mdDialog_,){
$rootScope = _$rootScope_
$scope = $rootScope.$new()
$mdDialog = _$mdDialog_
responsesController = _$controller_('responsesController', { $scope, $mdDialog })
}));
describe("First test" , function() {
it("Tests to see if tests are working", function() {
expect('test').toEqual('test');
});
});
});
But I am receiving this error:
Error: [$injector:unpr] Unknown provider: $mdDialogProvider <- $mdDialog
The module itself doesn't inject any dependencies:
export default angular
.module('respondent.projects.project.responses', [])
.controller('responsesController', responsesController)
....
However ngMaterial is injected in the main app module:
const app = angular.module('app', [
'ngMaterial',
...
]
Here is my karma.conf.js:
// Karma configuration
var webpackConfig = require('./webpack.config.js');
webpackConfig.entry = {};
var puppeteer = require('puppeteer');
process.env.CHROME_BIN = puppeteer.executablePath();
module.exports = function (config) {
config.set({
webpack: webpackConfig,
basePath: '',
plugins: [
'karma-chrome-launcher',
'karma-jasmine',
'karma-mocha-reporter',
'karma-babel-preprocessor',
'karma-webpack',
],
files: [
'node_modules/angular/angular.js',
'node_modules/angular-mocks/angular-mocks.js',
'apps/legacy/researcher/modules/projects/project/responses/module.js',
'apps/legacy/**/*.test.js',
],
exclude: [],
preprocessors: {
'apps/legacy/researcher/modules/projects/project/responses/module.js': ['webpack'],
'apps/legacy/**/*.test.js': ['babel'],
},
babelPreprocessor: {
options: {
presets: ['#babel/preset-env'],
sourceMap: 'inline',
},
},
reporters: ['mocha'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['ChromeHeadless'],
singleRun: false,
concurrency: Infinity,
});
};
What is the correct way to provide ngMaterial and/or $mdDialog to the controller for testing?
I am trying to run test cases for my application but stuck in between. Its giving the below error -
Error: [$injector:modulerr] Failed to instantiate module ng due to:
TypeError: 'undefined' is not an object (evaluating 'Function.prototype.bind.apply')
.......
......
{path}/test/unit/generate-form-directive.js:24
Test file is (generate-form-directive.js) -
describe("UNIT DIRECTIVE: generateForm", function () {
"use strict";
// Angular injectables
var $compile, $rootScope, $httpBackend;
// Module defined (non-Angular) injectables
var $scope, directiveScope, pagerVm;
// Local variables used for testing
var template;
// Initialize modules
beforeEach(function () {
module("TestDataModule");
});
beforeEach(function () {
inject(function (_$compile_, _$rootScope_, _$httpBackend_) {
$compile = _$compile_;
$rootScope = _$rootScope_;
$httpBackend = _$httpBackend_;
}); //Line no 24
});
it("test message", function() {
console.log("Hello");
});
});
My Karma file (karma.conf.js) -
module.exports = function (config) {
config.set({
basePath: "",
frameworks: ["mocha", "chai", "sinon"],
files: [
"node_modules/angular/angular.js",
"node_modules/angular-mocks/angular-mocks.js",
// Add template files
"src/**/*.html",
"src/commons/js/*.js",
"src/commons/services/*.js",
"src/commons/directives/**/*.js",
"src/modules/**/*.js",
// Add all the test files
"test/unit/*.js",
],
exclude: [],
preprocessors: {
"src/**/*.js": "coverage"
},
reporters: ["mocha", "coverage"],
mochaReporter: {
// full, autowatch, minimal
output: "autowatch",
ignoreSkipped: false
},
browserNoActivityTimeout: 20000,
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ["PhantomJS"],
singleRun: true,
coverageReporter: {
dir: "./coverage",
reporters: [{
type: "cobertura",
subdir: ".",
file: "cobertura.xml"
}, {
type: "text"
}]
}
});
};
Thanks in advance.
I had the same problem. The minimatch pattern ('/**/*') did not worked in karma.conf.js.
You have two options:
1) Try to change your minimatch version and see if it helps.
2) Or specify each file instead of using the minimatch pattern ("/**/*.js").
Change karma configuration file for something like this:
// Add template files
"src/views/view1.html",
"src/views/view2.html",
"src/commons/js/myJs1.js",
"src/commons/services/service1.js",
"src/commons/services/service2.js",
"src/commons/directives/directive1.js",
"src/modules/moduleName/moduleNAme1.js",
// Add all the test files
"test/unit/testFile1.js",
I've created a simple test application that write hello.
The application is:
boot.js
require.config({
appDir: '',
baseUrl: '',
paths: {
angular: 'app/bower_components/angular/angular',
Controller: 'app/js/Controller'
},
shim: {
'angular': {'exports': 'angular'}
},
config: {
},
priority: [
"angular"
]
});
require(['app/js/Module'], function()
{
console.log("Loaded!");
});
Module.js:
(function(define) {
"use strict";
define(['angular', 'Controller'],
function(angular, NccController) {
var app, appName = 'myApp';
app = angular
.module(appName, [])
.controller('Controller', NccController);
angular.bootstrap(document.getElementsByTagName("body")[0], [appName]);
return app;
});
}(define));
Controller.js
(function(define) {
"use strict";
define([], function()
{
var NccController = function($scope)
{
$scope.message = "ciao"; //data to graph
};
return NccController;
});
}(define));
The content of karma.conf.js is:
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'],
// list of files / patterns to load in the browser
files: [
{pattern: 'public_html/app/bower_components/angular/angular.js', included: false}
'test-main.js',
{pattern: 'public_html/app/js/*.js', included: false},
{pattern: 'public_html/app/test/**/*Spec.js', included: false},
],
// list of files to exclude
exclude: [
'public_html/app/js/boot.js'
],
// 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
});
};
the test-main.js is
var allTestFiles = [];
var TEST_REGEXP = /(spec|test)\.js$/i;
var pathToModule = function(path) {
return path.replace(/^\/base\//, '').replace(/\.js$/, '');
};
Object.keys(window.__karma__.files).forEach(function(file) {
if (TEST_REGEXP.test(file)) {
// Normalize paths to RequireJS module names.
allTestFiles.push(pathToModule(file));
}
});
require.config({
// Karma serves files under /base, which is the basePath from your config file
baseUrl: '/base',
paths: {
'angular': 'public_html/app/bower_components/angular/angular',
'Module': 'public_html/app/js/Module',
'Controller': 'public_html/app/js/Controller',
},
// dynamically load all test files
deps: allTestFiles,
// we have to kickoff jasmine, as it is asynchronous
callback: window.__karma__.start
});
the MainSpec.js is:
define(['Module','Controller'], function(angular,Module,Controller) {
describe('Controller', function(){
beforeEach(module('myApp'));
it('should print hello', inject(function($controller) {
var scope = {},
ctrl = $controller('Controller', {$scope:scope});
expect(scope.message).toBe('ciao');
}));
});
});
But when i run the test i obtain:
/usr/local/lib/node_modules/karma/bin/karma start
INFO [karma]: Karma v0.12.17 server started at http://localhost:9876/
INFO [launcher]: Starting browser Chrome
INFO [Chrome 36.0.1985 (Mac OS X 10.8.5)]: Connected on socket 14waTQA-kAa0VgYpvBBk with id 39770086
Chrome 36.0.1985 (Mac OS X 10.8.5) ERROR
Uncaught TypeError: Cannot read property 'module' of undefined
at /Users/daniele/Desktop/JARK/public_html/app/js/Module.js:8
What's wrong????
Thank you a lot.
Great tbranyen,
you've solved my great problem after 2 days of configuration. I post here all codes because I think that there're a lot of people that want to use angular/karma/RequireJs but have a lot of difficulty to setup all.
So boot.js, Module.js and controller.js are the same otherwise the file:
karma.conf.js is:
// Karma configuration
// Generated on Sat Jul 26 2014 18:36:34 GMT+0200 (CEST)
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'],
// list of files / patterns to load in the browser
files: [
{pattern: 'public_html/app/bower_components/angular/angular.js', included: false},
{pattern: 'public_html/app/bower_components/angular-mocks/angular-mocks.js', included: false},
{pattern: 'public_html/app/js/*.js', included: false},
{pattern: 'public_html/app/test/**/*Spec.js', included: false},
'test-main.js',
],
// list of files to exclude
exclude: [
'public_html/app/js/boot.js'
],
// 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.main.js is:
var allTestFiles = [];
var TEST_REGEXP = /(spec|test)\.js$/i;
var pathToModule = function(path) {
return path.replace(/^\/base\//, '').replace(/\.js$/, '');
};
Object.keys(window.__karma__.files).forEach(function(file) {
if (TEST_REGEXP.test(file)) {
// Normalize paths to RequireJS module names.
allTestFiles.push(pathToModule(file));
}
});
require.config({
// Karma serves files under /base, which is the basePath from your config file
baseUrl: window.__karma__ ? "/base/" : "/",
paths: {
'angular': 'public_html/app/bower_components/angular/angular',
'angular-mocks': 'public_html/app/bower_components/angular-mocks/angular-mocks',
'Module': 'public_html/app/js/Module',
'Controller': 'public_html/app/js/Controller',
},
shim: {
'angular': {'exports': 'angular'},
'angular-mocks': ['angular']
},
});
require(['angular-mocks'], function() {
require(allTestFiles, window.__karma__.start);
});
and MainSpec.js is:
define(['angular','angular-mocks','Module','Controller'], function(angular,mocks,Module,Controller) {
describe('Controller', function(){
beforeEach(module('myApp'));
it('should print hello', inject(function($controller) {
var scope = {},
ctrl = $controller('Controller', {$scope:scope});
expect(scope.message).toBe('ciao');
}));
});
});
I hope that can help same people that want use it
Karma serves files under the /base/ root path, not /. You need to change your baseUrl property within the RequireJS configuration to be baseUrl: "/base/".
A simple way of handling this conditionally is:
baseUrl: window.__karma__ ? "/base/" : "/"
Edit:
I'm incorrect with the above, you have it configured correctly. The only other guess I have is that deps is loading your tests before the configuration has finished being set. Although you have mentioned that Angular loads 200 OK. My recommendation here would be to try extracting the test loading away from deps and instead break the configuration and loading into two different operations.
require.config({
"paths": { "angular": "<path/to/angular>" }
});
require(allTestFiles, function() {
window.__karma__.start();
});
I would also remove the callback from the karma Require configuration.
Edit 2:
Another recommendation would be to share your main application configuration so that you don't have to declare paths over again. An example of how this would look is:
https://gist.github.com/tbranyen/e37a7d888f7f90c25e63#file-config-js-L27-L28
Edit 3 (Hopefully last):
After debugging the project the error ended up being a missing Angular shim configuration in the test-main.js file.
Look at this project that uses requirejs and karma for angular js. Try and follow the set up. https://github.com/adikari/angular-seed
I am trying to configure my karma jasmine unit testing with requirejs. But each time i run it, i am getting the below error:
Chrome 34.0.1847 (Mac OS X 10.9.2) ERROR
Uncaught Error: Mismatched anonymous define() module: function (angular){
describe('Unit: Testing RequireJS', function(){
var ctrl;
var scope;
var rootScope;
beforeEach(angular.mock.module('wsaApp'));
beforeEach(angular.mock...<omitted>...ch
Below are differenr file:
spec file:
define(['angular'], function(angular){
describe('Unit: Testing RequireJS', function(){
var ctrl;
var scope;
var rootScope;
beforeEach(angular.mock.module('wsaApp'));
beforeEach(angular.mock.inject(function($rootScope){
scope = $rootScope.$new();
rootScope = $rootScope;
}));
});
});
main.js
require.config({
paths: {
/* ABC order */
'angular': 'vendor/angular/1.2.0/angular.min'
},
shim: {
'angular': { exports: 'angular' },
'app/controllers': { deps: ['angular'] }
}
});
test-main.js
// This creates an array of all the files that Karma finds with a suffix of
// Test.js (eg utilsTest.js) to be added to the Require JS config below
var tests = [],
file;
for (file in window.__karma__.files) {
if (window.__karma__.files.hasOwnProperty(file)) {
if(/spec\.js$/.test(file)) {
tests.push(file);
}
}
}
requirejs.config({
baseUrl: '/base/public/javascripts/', // Karma serves files from /base/<your-base-path>
paths: {
/* ABC order */
'angular': 'vendor/angular/1.2.1/angular.min'
},
shim: {
'angular': { exports: 'angular' },
'app/controllers': { deps: ['angular'] },
},
deps: tests, // add tests array to load our tests
callback: window.__karma__.start // start tests once Require.js is done
});
karma.conf.js
//Karma configuration
module.exports = function (config) {
config.set({
// base path, that will be used to resolve files and exclude
basePath: '',
// Fix for "JASMINE is not supported anymore" warning
frameworks: ["jasmine", "requirejs"],
// list of files / patterns to load in the browser
files: [
'vendor/angular/1.2.1/angular.js',
'jquery-1.7.1.min.js',
'test/spec/**/*.js',
'test/test-main.js'
],
preprocessors: {
'app/**/*.js': 'coverage'
},
// list of files to exclude
exclude: ['app/main.js'],
// test results reporter to use
// possible values: dots || progress || growl
reporters: ['progress', 'coverage'],
coverageReporter : {
type: 'html',
dir: 'coverage/'
},
// web server port
port: 9876,
// cli runner port
runnerPort: 9100,
// enable / disable colors in the output (reporters and logs)
colors: true,
// 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: false,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers: ['Chrome'],
browserNoActivityTimeout: 100000,
// If browser does not capture in given timeout [ms], kill it
captureTimeout: 20000,
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: true
});
}
i have tried different options mentioned in other threads, but nothing seems to work.
Finally i solved all the issues and was able to run the jasmine test successfully with requirejs configuration. I had top mention all the dependencies in the karma config and mark them as included: false exclusively so that they get loaded by requirejs through my test-config file.
files: [
{pattern: 'vendor/angular/1.2.1/angular.js', included: false},
{pattern: 'vendor/angular/1.2.1/angular-mocks.js', included: false},
{pattern: 'vendor/angular/1.2.1/angular-*.js', included: false},
{pattern: 'vendor/bootstrap/bootstrap-*.js', included: false},
{pattern: 'jquery-1.7.1.min.js', included: false},
{pattern: 'app/app.js', included: false},
{pattern: 'app/**/*.js', included: false},
{pattern: 'test/test-config.js', included: true}]
only the test-config is loaded through karma and all others to be included in the karma config but mark as false.
Also, i had to load the app.js in my spec file so that the modules and controllers get loaded:
define(['angular-mocks', 'jquery', 'app/app'], function(angularmocks, $, app){
describe.....
}
Since you're loading the specific .js files you need in your test-main.js with the paths: { } parameter, you don't have to explicitly list them in karma.config.js. Instead, you can just use your line { pattern: 'app/**/*.js', included: false }. All the lines before that are redundant. Just make sure you have the included: false modifier, otherwise Karma will load them in-line, and you'll get the Uncaught Error: Mismatched anonymous define() problem
I keep trying to run some E2E tests out of ToT angular-seed master and keep getting the following error when I run ./scripts/e2e-test.sh:
TypeError: Property 'browser' of object #<Object> is not a function
I get this error when trying to run the following piece of code as one of my e2e scenario:
'use strict';
/* https://github.com/angular/protractor/blob/master/docs/getting-started.md */
describe('MyApp', function() {
describe(Index', function() {
beforeEach(function() {
browser().navigateTo('/');
});
it('should render feature specific image', function() {
expect(element('img.featurette-image').length).toBe('4');
});
});
});
I'm wondering if my protractor config is incorrect:
exports.config = {
allScriptsTimeout: 11000,
specs: [
'../test/e2e/*.js'
],
capabilities: {
'browserName': 'chrome'
},
baseUrl: 'http://localhost:3000/',
framework: 'jasmine',
jasmineNodeOpts: {
defaultTimeoutInterval: 30000
}
};
My unit tests are running just fine. This is the Karma config I have for them (note that this is an angular app within the public director of a sinatra application listening on port 3000:
module.exports = function(config){
config.set({
basePath : '../',
files : [
'https://code.jquery.com/jquery-1.10.2.min.js',
'app/lib/angular/angular.js',
'app/lib/angular/angular-*.js',
'test/lib/angular/angular-mocks.js',
'app/js/**/*.js',
'test/unit/**/*.js'
],
exclude : [
'app/lib/angular/angular-loader.js',
'app/lib/angular/*.min.js',
'app/lib/angular/angular-scenario.js'
],
autoWatch : true,
frameworks: ['jasmine'],
browsers : ['Chrome'],
plugins : [
'karma-junit-reporter',
'karma-chrome-launcher',
'karma-firefox-launcher',
'karma-jasmine'
],
junitReporter : {
outputFile: 'test_out/unit.xml',
suite: 'unit'
}
})}
Thanks for the help!
You need to change this line:
browser().navigateTo('/');
to
browser.navigateTo('/');
That's it.