Angularjs unit testing with Karma - javascript

Having a few issues with testing a directive - our application is trying to be modular hence the need for module.exports which exports the angular module;
module.exports = angular.module('project', [])
.config(function ($stateProvider) {
$stateProvider
.state('alive', {
url: '/college',
templateUrl: 'dashboard.html',
controller: 'CollegeCtrl',
authenticate: true
});
})
.factory('College', require('./services/college.service.js'))
.controller('CollegeCtrl', require('./dashboard/college.controller.js'))
.directive('collegeTile', require('./dashboard/tile/tile.directive.js'))
.run(function ($rootScope, SideFactory) {
SideFactory.push({
'priority': 1,
'icon': 'fa-th-large'
});
});
Directive looks like this;
<div class="thumbnail" ng-click="openProject(college._id)">
<span>{{college}}</span>
</div>
</div>
The directive spec looks like this - note, the templates loads in all the html templates;
'use strict';
describe('Directive: tile', function () {
var $compile;
var $scope;
// load the directive's module and view
beforeEach(module('ui.router'));
beforeEach(module('project'));
beforeEach(module('templates'));
// Create the SideFactory
beforeEach(module(function ($provide) {
var sideFactory = {
push: function () {
}
};
$provide.value('SideFactory', sideFactory);
}));
beforeEach(inject(function (_$compile_, _$rootScope_) {
$compile = _$compile_;
$scope = _$rootScope_.$new();
}));
it("should validate to true", function () {
expect(true).toBe(true);
});
});
I get the following error when running karma;
TypeError: 'undefined' is not a function (evaluating 'expect(true).toBe(true)')
Karma config;
module.exports = function (config) {
config.set({
// base path, that will be used to resolve files and exclude
basePath: '',
// testing framework to use (jasmine/mocha/qunit/...)
frameworks: ['jasmine', 'chai'],
// list of files / patterns to load in the browser
files: [
'dev/assets/bundle.js',
'angular-mocks/angular-mocks.js',
'sample/client/*.html',
'sample/client/*.spec.js',
'client/**/*.html',
'client/**/*.spec.js'
],
preprocessors: {
'client/**/*.html': ['ng-html2js']
},
ngHtml2JsPreprocessor: {
// strip this from the file path
stripPrefix: 'client/',
prependPrefix: 'college/',
// setting this option will create only a single module that contains templates
// from all the files, so you can load them all with module('foo')
moduleName: 'templates'
},
// list of files / patterns to exclude
exclude: [],
// test results reporter to use
// possible values: 'dots', 'progress', 'junit'
reporters: ['progress', 'coverage'],
coverageReporter: {
type: 'html',
dir: 'coverage'
},
// enable / disable colors in the output (reporters and logs)
colors: true,
// web server port
port: 8080,
// level of logging: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel: 'INFO',
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// - IE (only Windows)
browsers: ['PhantomJS'],
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false
});
};

Related

karma angular templateUrl not found

I've some problems when testing angular directives with karma, the problem is that when comes from templateUrl never translate it.
here is my karma.conf.js
'use strict';
var wiredep = require('wiredep');
var bowerFiles = wiredep().js;
var appFiles = [
'src/modules/**/*-module.js',
'src/modules/**/**/*.js',
{ pattern: 'src/modules/**/*.mol', watched: true, served: true, included: false },
'src/modules/**/**/templates/*.html',
{
pattern: '../src/assets/images/*.*',
watched: false,
included: false,
served: true
},
'src/modules/**/**/templates/*.html'
];
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',
'sinon-chai'
],
junitReporter: {
outputFile: '../reports/test-results/test-results.xml'
},
coverageReporter: {
dir: 'reports/test-coverage/',
subdir: function (browser) {
// normalization process to keep a consistent browser name across different OS
return browser.toLowerCase().split(/[ /-]/)[0];
},
check: {
global: {
statements: 10,
branches: 1,
functions: 10,
lines: 10
},
each: {
statements: 0,
branches: 0,
functions: 0,
lines: 0
}
},
reporters: [
{ type: 'html', file: 'coverage.html' },
{ type: 'cobertura', file: 'coverage.xml' },
{ type: 'json' },
{ type: 'text-summary' }
]
},
reporters: ['junit', 'dots', 'coverage'],
// list of files / patterns to load in the browser
files: [].concat(bowerFiles, appFiles),
// 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: {
'src/modules/**/**/!(*.test).js': 'coverage',
'src/modules/**/**/templates/*.html': ['ng-html2js']
},
ngHtml2JsPreprocessor: {
stripPrefix: 'src/',
moduleName: 'templates'
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
// 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
});
};
And the test ...
'use strict';
describe('dra-header-directive', function () {
var compile;
var rootScope;
var templateCache;
beforeEach(module('dd'));
beforeEach(module('templates'));
beforeEach(inject(function ($compile, $rootScope, $templateCache) {
compile = $compile;
rootScope = $rootScope;
templateCache = $templateCache;
}));
it('Replace the element with the appropiate element', function () {
var scope = rootScope.$new();
var el = angular.element('<testing></testing><dra-header></dra-header><input-bar></input-bar>');
var element = compile(el)(scope);
scope.$digest();
console.log(element);
});
});
The first tag is translated due to is not defined as templateUrl, but the others don't.
if I get the templates with $templateCache I can read the content, so I asume ng-html2js is doing it's job. any ideas?
Thanks for helping!
Its solved, I changed the before each module to avoid importing unnecesary module dependencies, looks like there was something that was modifying my rootScope, I just loaded the module that has the directive, and now works fine
'use strict';
describe('dra-header-directive', function () {
var compile;
var scope;
var templateCache;
beforeEach(module('dra.components.DRAHeaderModule'));
beforeEach(function () {
module('templates');
});
beforeEach(inject(function ($compile, $rootScope, $templateCache) {
compile = $compile;
templateCache = $templateCache;
scope = $rootScope.$new();
}));
it('Replace the element with the appropiate element', function () {
var el = angular.element('<dra-header></dra-header>');
compile(el)(scope);
scope.$digest();
expect(el.find('div')[0]).to.not.be.undefined();
});
});

TypeError: $httpBackend is undefined

I am developing an angular application. I have the application running with few controllers and services. Now I wanted to start unit testing the services and controllers. But don't know what I am doing wrong, I am not able to run a test properly for a even a single service. When I try to run the test using karma using:
karma start karma.conf.js
I get following error:
Firefox 38.0.0 (Windows 7 0.0.0) service: MyCategoryService should send a request to MyCategoryService FAILED
minErr/<#c:/Users/bgurung2/workspace/admintoolui/src/main/webapp/bower_components/angular/angular.js:68:12
loadModules/<#c:/Users/bgurung2/workspace/admintoolui/src/main/webapp/bower_components/angular/angular.js:4458:15
forEach#c:/Users/bgurung2/workspace/admintoolui/src/main/webapp/bower_components/angular/angular.js:340:11
loadModules#c:/Users/bgurung2/workspace/admintoolui/src/main/webapp/bower_components/angular/angular.js:4419:5
createInjector#c:/Users/bgurung2/workspace/admintoolui/src/main/webapp/bower_components/angular/angular.js:4344:11
workFn#c:/Users/bgurung2/workspace/admintoolui/src/main/webapp/js/libs/angular-mocks.js:2797:44
angular.mock.inject#c:/Users/bgurung2/workspace/admintoolui/src/main/webapp/js/libs/angular-mocks.js:2777:30
#c:/Users/bgurung2/workspace/admintoolui/src/main/webapp/js/tests/services/preferenceCategoryService.test.js:18:9
TypeError: $httpBackend is undefined in c:/Users/bgurung2/workspace/admintoolui/src/main/webapp/js/tests/services/preferenceCategoryServi
ce.test.js (line 33)
#c:/Users/bgurung2/workspace/admintoolui/src/main/webapp/js/tests/services/preferenceCategoryService.test.js:33:9
Firefox 38.0.0 (Windows 7 0.0.0): Executed 13 of 13 (1 FAILED) (0.016 secs / 0.039 secs)
I am not sure where did I go wrong. I tried to follow this stackoverflow question but was out of clue.
Any help or suggestion would be great!!
Here is my app:
'use strict';
/* App Module */
var app = angular.module('myApp', [
'ngRoute', // uri routing
'controllers', // controllers
'services', // services
'ngMock'
]);
// module controllers
var appCtrl = angular.module('controllers', []);
// module services
var appServices = angular.module('services', [ 'ngResource' ]);
Here is my service:
'use strict';
appServices.factory('MyCategoryService', ['$resource', 'REST_RESOURCE',
function ($resource, REST_RESOURCE) {
return $resource(REST_RESOURCE.PREFERENCE, {}, {
query: {
method: 'GET',
params: {},
isArray: false
}
});
}]);
Here is my Service Spec:
describe('service: MyCategoryService', function () {
var $httpBackend;
var $rootScope;
var MyCategoryService;
var REST_RESOURCE;
beforeEach(function () {
angular.mock.module('myApp');
angular.mock.inject(function ($injector) {
$httpBackend = $injector.get('$httpBackend');
$rootScope = $injector.get('$rootScope');
MyCategoryService= $injector.get('MyCategoryService');
REST_RESOURCE = $injector.get('REST_RESOURCE');
});
});
it('should send a request to MyCategoryService', function () {
//TODO
var mockdata = {
items: {
}
};
$httpBackend.expect('GET', REST_RESOURCE.PREFERENCE).respond(200, mockdata);
MyCategoryService.query(function (response) {
$rootScope.data = response.items;
});
$httpBackend.flush();
expect($rootScope.data).toEqual(mockdata);
});
});
Here is my karma.conf.js file:
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: [
//dependencies
'bower_components/angular/angular.js',
'bower_components/angular-mocks/angular-mocks.js',
'bower_components/angular-route/angular-route.js',
'bower_components/angular-bootstrap/ui-bootstrap.js',
'bower_components/angular-bootstrap/ui-bootstrap-tpls.js',
'bower_components/angular-cookies/angular-cookies.js',
'js/app.js',
'js/libs/*.js',
'js/directives/*.js',
'js/routes.js',
'js/resource_uri.js',
'js/services/*.js',
'js/controllers/*.js',
//test files
'js/tests/*.test.js',
'js/tests/*/*.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'],
// 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: ['Firefox'],
// 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
});
};
I finally got my test running after going through some changes in some files. I don't know what the exact reason was, but I got it working with the following changes. Here's my changes below:
I removed ngMocks dependency. After changes, my app.js file looks like following.
'use strict';
/* App Module */
var app = angular.module('admintool', [ 'ngRoute', // uri routing
'controllers', // controllers
'services', // services
'angularUtils.directives.dirPagination', // pagination service
'ui.bootstrap', // angular ui bootstrap
'ui', // ui sortable
'uiSwitch', // on of switch service
'ngMessages', // for form validation
'xeditable', // for table edit
'ngCookies'
// messages
]);
// module controllers
var appCtrl = angular.module('controllers', []);
// module services
var appServices = angular.module('services', [ 'ngResource' ]);
service.js looks like:
'use strict';
//appServices.factory('PreferenceCategory', ['$resource', 'REST_RESOURCE',
angular.module('services').factory('PreferenceCategory', ['$resource', 'REST_RESOURCE',
function ($resource, REST_RESOURCE) {
return $resource(REST_RESOURCE.PREFERENCE_CATEGORY, {}, {
query: {
method: 'GET',
params: {},
isArray: false
}
});
}]);
serviceSpec.js looks like:
describe('Preference Category Service',
function() {
beforeEach(angular.mock.module("admintool"));
var httpBackend, pc;
beforeEach(inject(function($httpBackend, PreferenceCategory) {
httpBackend = $httpBackend;
pc = PreferenceCategory;
}));
afterEach(function() {
httpBackend.verifyNoOutstandingExpectation();
httpBackend.verifyNoOutstandingRequest();
});
it(
'Check GET Request',
function() {
httpBackend
.expectGET(
'http://jboss-pmadmin-tool-dev.ose-core.optum.com/pmadmin-tool/v1/preference_categories')
.respond({
username : 'test'
});
// call the function on our service instance
var response = pc.query();
httpBackend.flush();
expect(response.username).toEqual('test');
});
});
karma.conf.js file, I removed 'js/libs/*' and added individual files that are used in the app.
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files,
// exclude)
basePath : '../admintoolui/src/main/webapp/',
// 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.min.js',
'bower_components/angular-mocks/angular-mocks.js',
'js/libs/angular-resource.js',
'bower_components/angular-route/angular-route.js',
'bower_components/angular-bootstrap/ui-bootstrap.js',
'js/libs/pagination.js',
'js/libs/angular-ui.js',
'js/libs/angular-ui-switch.min.js',
'js/libs/angular-messages.js',
'js/libs/xeditable.min.js',
'bower_components/angular-cookies/angular-cookies.js',
'js/app.js',
'js/resource_uri.js',
'js/services/*.js',
'js/controllers/*.js',
'js/tests/**/*.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' ],
// 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 : [ 'Firefox' ],
// 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
})
}

Testing services from $resource using factory with Karma

I'm new to karma and I'm trying to run tests in order to check if my factories are set to the proper value returned by the API.
apiServices.js :
'use strict';
angular.module('balrogApp.services', ['balrogApp.config'])
.factory('Requests', ['$resource', 'balrogConfig', function($resource, balrogConfig) {
return $resource(balrogConfig.backend + '/requests/:id', {id: '#id'});
}])
.factory('Projects', ['$resource', 'balrogConfig', function($resource, balrogConfig) {
return $resource(balrogConfig.backend + '/projects/:id', {id: '#id'}, {'update': { method:'PUT' }});
}])
.factory('Users', ['$resource', 'balrogConfig', function($resource, balrogConfig) {
return $resource(balrogConfig.backend + '/users/:id', {id: '#id'});
}]);
config.js :
'use strict';
angular.module('balrogApp.config', [])
.constant('balrogConfig', {
'backend': 'http://127.0.0.1:8000/api/catalog'
});
Now, I've been through a few articles about $resource and karma but I didn't really get how to set up the unit tests for my case.
Here is my test file : (edited after #Freezystem answer)
describe("Services test", function () {
var Requests, Projects, Users;
beforeEach(function () {
angular.mock.module("balrogApp.services");
angular.mock.inject(function (_Requests_, _Projects_, _Users_) {
Requests = _Requests_;
Projects = _Projects_;
Users = _Users_
});
});
it("API factories must be defined", function () {
expect(Requests).toBeDefined();
expect(Projects).toBeDefined();
expect(Users).toBeDefined();
});
});
I also tried a few things with $httpBackend but couldn't make it neither.
How to make this work in order to know if the services are working.
Also, how to check if the services are returning the expected response from the API ?
Edit : Adding karma.conf.js :
// Karma configuration
// Generated on Tue Nov 17 2015 13:48:48 GMT+0100 (Romance 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: [
'bower_components/jquery/dist/jquery.js',
'bower_components/angular/angular.js',
'bower_components/angular-animate/angular-animate.js',
'bower_components/angular-aria/angular-aria.js',
'bower_components/angular-material/angular-material.js',
'bower_components/angular-messages/angular-messages.js',
'bower_components/angular-mocks/angular-mocks.js',
'bower_components/angular-resource/angular-resource.js',
'bower_components/angular-route/angular-route.js',
'bower_components/angular-sanitize/angular-sanitize.js',
'bower_components/angular-bootstrap/ui-bootstrap.js',
'bower_components/ui-select/dist/select.js',
'bower_components/angular-smart-table/dist/smart-table.js',
'bower_components/angular-ui-switch/angular-ui-switch.js',
'bower_components/angular-growl-v2/build/angular-growl.js',
'bower_components/angular-number-picker/angular-number-picker.js',
'bower_components/moment/moment.js',
'app/*.js',
'app/**/*.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'],
plugins: [
'karma-jasmine',
'karma-chrome-launcher',
'karma-firefox-launcher'
],
// 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
})
};
So far, I'm getthing this error : http://codepen.io/anon/pen/OyqWdE
Just try to inject each factory by its own name :
describe("Services test", function () {
var users, $httpBackend;
beforeEach(function(){
angular.mock.module('balrogApp.services');
angular.mock.inject(function (_Users_, _$httpBackend_) {
users = _Users_;
$httpBackend = _$httpBackend_;
});
});
// clear all outstanding requests after each tests
afterEach(function() {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
it("Factories must be defined", function () {
// simulate API response
$httpBackend.when('/api/catalog/users/1337')
.respond( 200, { id : 1337, name : 'Tom' } );
// there is a better way to do it actually but I'm unable to make it work
// $httpBackend.whenRoute('GET', '/api/catalog/users/:id')
// .respond(function ( method, url, data, headers, params ) {
// return [ 200, { user : params.id } ] ;
// });
// make the user request to the API
var user = users.get({id:1337});
$httpBackend.flush();
// test API returned Object
expect(user.id).toBe(1337);
expect(user.name).toBe('Tom');
});
});
Let me know if you have any other questions.

error with mocha karma test runner

My directory structure is:
karma.conf.js
GruntFile.js
src
-MyModule.js
lib
-bar.js
test
-MyModule.test.js
-test-main.js
This is my karma.conf.js file
// Karma configuration
// Generated on Sat Aug 08 2015 08:09:40 GMT+0530 (IST)
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', 'requirejs','chai'],
// list of files / patterns to load in the browser
files: [
{pattern: 'lib/**/*.js', included: false},
{pattern: 'src/**/*.js', included: false},
{pattern: 'test/**/*.test.js', included: false},
'test/test-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: false,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: [],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
})
}
this is lib/bar.js
module.exports = function (a, b) {
return a+b;
}
this is src/MyModule.js
var bar = require("../lib/bar.js");
module.exports={
add:function add (a, b) {
return bar(a, b);
}
}
and this is test/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',
paths: {
'../src/MyModule.js': '../src/MyModule.js',
'../lib/bar.js': '../lib/bar.js'
},
deps: allTestFiles,
callback: window.__karma__.start
});
and this is the test/MyModule.test.js
var MyModule = require('../src/MyModule.js');
describe('A test suite', function () {
var expect = window.expect;
beforeEach(function () {
});
afterEach(function () {
});
it('should add the two numbers', function () {
var abc = MyModule.add(1, 3);
expect(abc).to.be.equal(4);
});
});
When I am running the test I get the error
Error: Module name "../src/MyModule.js" has not been loaded yet for context: _. Use require([])
where am I going wrong?
the function add() somehow needs be accessible from within the local scope of the test, eg.:
describe('A test suite', function() {
/* ... */
var add = function(a, b) {return a+b;};
/* ... */
});
alternatively, the require() function can be used to load further scripts.

Karma unit test tries to send a request to a completely different module

I have the following karma test for the angular-fullstack scaffold:
describe('Directive: categoryLookAhead', function () {
// load the directive's module and view
beforeEach(module('portfolioApp'));
beforeEach(module('app/article/Directives/categoryLookAhead/categoryLookAhead.html'));
var element, scope;
beforeEach(inject(function ($rootScope) {
scope = $rootScope.$new();
}));
it('should make hidden element visible', inject(function ($compile) {
element = angular.element('<category-look-ahead></category-look-ahead>');
element = $compile(element)(scope);
scope.$apply();
expect(element.text()).not.toBe(null);
}));
});
and this is 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: '',
// testing framework to use (jasmine/mocha/qunit/...)
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'client/bower_components/jquery/dist/jquery.js',
'client/bower_components/angular/angular.js',
'client/bower_components/angular-mocks/angular-mocks.js',
'client/bower_components/angular-resource/angular-resource.js',
'client/bower_components/angular-cookies/angular-cookies.js',
'client/bower_components/angular-sanitize/angular-sanitize.js',
'client/bower_components/angular-route/angular-route.js',
'client/bower_components/angular-bootstrap/ui-bootstrap-tpls.js',
'client/bower_components/lodash/dist/lodash.compat.js',
'client/bower_components/angular-socket-io/socket.js',
'client/bower_components/angular-ui-router/release/angular-ui-router.js',
'client/bower_components/angular-markdown/angular.markdown.js',
'client/bower_components/angular-ui-router-title/angular-ui-router-title.js',
'client/app/app.js',
'client/app/app.coffee',
'client/app/**/*.js',
'client/app/**/*.coffee',
'client/components/**/*.js',
'client/components/**/*.coffee',
'client/app/**/*.jade',
'client/components/**/*.jade',
'client/app/**/*.html',
'client/components/**/*.html'
],
preprocessors: {
'**/*.jade': 'ng-jade2js',
'**/*.html': 'html2js',
'**/*.coffee': 'coffee',
},
ngHtml2JsPreprocessor: {
stripPrefix: 'client/'
},
ngJade2JsPreprocessor: {
stripPrefix: 'client/'
},
// 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: false,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers: ['PhantomJS'],
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false
});
};
and this is the directive's controller:
angular.module('portfolioApp')
.directive('categoryLookAhead', function($interval, $filter) {
return {
templateUrl: 'app/article/Directives/categoryLookAhead/categoryLookAhead.html',
restrict: 'E',
scope: {
suggestedTags: '=',
selectedTags: '='
},
...
In my head, it should just compile from that template and start doing its thing but I get an error:
Error: Unexpected request: GET app/main/main.html
main.html does not include this directive at all, so I don't know why it's getting an unexpected request for this.
I've read in other StackOverflow posts that I can use whenGET(*).passThrough() to ignore these things, but I'd like to know why it's making a request to a module that has nothing to do with the directive.

Categories

Resources