I ran a jasmine test over angular js, and i get the next error:
PhantomJS 2.1.1 (Linux 0.0.0) test_servicioCalculadora should provide
a version FAILED
/home/ivan/workspace/mobile.trackphone/www/lib/ionic/js/ionic.bundle.js:13218:53
forEach#/home/ivan/workspace/mobile.trackphone/www/lib/ionic/js/ionic.bundle.js:9168:24
loadModules#/home/ivan/workspace/mobile.trackphone/www/lib/ionic/js/ionic.bundle.js:13178:12
createInjector#/home/ivan/workspace/mobile.trackphone/www/lib/ionic/js/ionic.bundle.js:13104:22
workFn#/home/ivan/workspace/mobile.trackphone/www/lib/angular-mocks/angular-mocks.js:3074:60
loaded#http://localhost:9876/context.js:151:17
I tried to change the routes, inject other service, and it's not working too
I ran other case like
it("compara un valor con otro", function () {
var pi = 3.1415926,
e = 2.78;
expect(e).toBeLessThan(pi);
expect(pi).not.toBeLessThan(e);
});
and this's working fine.
This is my test file
describe("test_servicioCalculadora", function () {
var calcu;
beforeEach(module('starter'));
it('should provide a version', inject(function(version) {
expect(version).toEqual('v1');
}));
});
my index.js is
var app = angular.module('starter', ['ionic', 'LocalStorageModule', 'btford.socket-io', 'angularMoment', 'ngCordova', 'ngAudio']);
app.value('version', 'v1');
my karma.config.js
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
files: [
'../www/lib/ionic/js/ionic.bundle.js',
'../www/lib/angular-mocks/angular-mocks.js',
'../www/js/index.js',
'../tests/**/*-test.js'
],
exclude: [
],
preprocessors: {
},
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_ERROR,
autoWatch: true,
browsers: ['PhantomJS'],
singleRun: false,
concurrency: Infinity
})
};
You are trying to inject a value. Should be a service or a factory.
e.g.
beforeEach(module('some.service', function($provide){
var log = {
info: function(data){
console.log(data);
}
}
$provide.value('$log', log);
});
beforeEach(inject(function(_serviceName_){
serviceName = _serviceName_;
}));
it("Actual test", function(){
serviceName.performAction();
});
See the example, first is the module where you can set some values. Then is the service or factory at the end the test.
This mean that the value of log will be injected on serviceName when is used on the actual test.
Hope this help to clarify.
Related
Under my Angular 6 app , i ve this config
karma.conf.js:
// Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '#angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('#angular-devkit/build-angular/plugins/karma')
],
client:{
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
mime: {
'text/x-typescript': ['ts','tsx']
},
coverageIstanbulReporter: {
dir: require('path').join(__dirname, 'coverage'),
reports: [ 'html', 'lcovonly' ],
fixWebpackSourcePaths: true
},
reporters: config.angularCli && config.angularCli.codeCoverage
? ['progress', 'coverage-istanbul']
: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
browserDisconnectTimeout: 10000,
browserDisconnectTolerance: 3,
browserNoActivityTimeout: 60000,
flags: [
'--disable-web-security',
'--disable-gpu',
'--no-sandbox'
],
singleRun: true,
concurrency: Infinity
});
};
An i ve a file , test.ts ; which is supposed to configurate the test running :
// This file is required by karma.conf.js and loads recursively all the .spec and framework files
import 'zone.js/dist/long-stack-trace-zone';
import 'zone.js/dist/proxy.js';
import 'zone.js/dist/sync-test';
import 'zone.js/dist/jasmine-patch';
import 'zone.js/dist/async-test';
import 'zone.js/dist/fake-async-test';
import { getTestBed } from '#angular/core/testing';
import {
BrowserDynamicTestingModule,
platformBrowserDynamicTesting
} from '#angular/platform-browser-dynamic/testing';
// Unfortunately there's no typing for the `__karma__` variable. Just declare it as any.
declare var __karma__: any;
declare var require: any;
// Prevent Karma from running prematurely.
__karma__.loaded = function () {};
// First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(
BrowserDynamicTestingModule,
platformBrowserDynamicTesting()
);
// Then we find all the tests.
const context = require.context('./', true, /my-component.component.spec.ts/);
// And load the modules.
context.keys().map(context);
// Finally, start Karma to run the tests.
__karma__.start();
i may let me filter file to be tested
for example i want to run this one : my-component.component.spec.ts
But that it not running , and it seems that it lacks some config in the karma.conf to run the test.ts
Sugesstions ?
change this line
const context = require.context('./', true, /my-component.component.spec.ts/);
with this
const context = require.context('./', true, /my-component\.component\.spec\.ts$/);
to avoid the special character '.'
I have a nw.js native application with angular.js inside. My app bundled with webpack and contains native node.js modules. My entry point is index.js file that I organized like this:
var gui = require('nw.gui');
var angular = require('angular');
require('./app.css');
// other modules
var myApp = angular.module('myApp', [
'ngRaven',
'ngMaterial',
'ngMessages'
]).constant(
'fs', require('fs')
)
require('./services')(myApp);
require('./directives')(myApp);
require('./factories')(myApp);
require('./filters')(myApp);
require('./controllers')(myApp);
require('./app.js')(myApp);
My webpack config looks like this:
const path = require('path');
const config = {
entry: [
'./app/index.js'
],
output: {
path: path.resolve(__dirname, 'app'),
filename: 'bundle.js'
},
devtool: "source-map",
target: 'node-webkit',
module:{
// css, html loaders
},
node: {
os: true,
fs: true,
child_process: true,
__dirname: true,
__filename: true
}
};
module.exports = config;
So every dependency include Node.js native modules like fs, path, child_process bundled in one big file bundle.js that i include in html and then package my nw.js app. So my app structure looks like:
my_project:
--app
----controllers
------welcome
--------welcome.js // Page controller
--------welcome.html // Page HTML
------index.js // here I include each page controller
----app.js // My angular app initialization
----index.js // here I include all dependencies
I'm trying to run tests with this structure. I tried karma+jasmine, karma+mocha, tried different configurations, my last one looks like:
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
files: [
'app/bundle.js',
'app/**/*spec.js'
],
exclude: [],
preprocessors: {
'app/bundle.js': ['webpack']
},
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['ChromeHeadlessNoSandbox'],
customLaunchers: {
ChromeHeadlessNoSandbox: {
base: 'ChromeHeadless',
flags: ['--no-sandbox']
}
},
singleRun: true,
webpack: {
// you don't need to specify the entry option because
// karma watches the test entry points
// webpack watches dependencies
// ... remainder of webpack configuration (or import)
},
webpackMiddleware: {
// webpack-dev-middleware configuration
// i.e.
noInfo: true,
// and use stats to turn off verbose output
stats: {
// options i.e.
chunks: false
}
}
});
};
But my tests still not see the angular application.
describe('Welcome page', function() {
beforeEach(angular.mock.module('WelcomePageCtrl'));
});
P.S I don't require exactly karma and jasminne, so any solution will be appreciated. I just want to cover my project with tests
I have gone through something similar myself. I don't think you need the bundle.js for your tests.
Here is how would do it:
I assume your controller/service/etc implementation is as follows:
/* app/controller/welcome.js */
module.exports = function(app) {
return app.controller("MyCtrl", function($scope) {
$scope.name = "lebouf";
});
};
I like my test code to sit right beside the code I'm testing (Welcome.spec.js in the same directory as Welcome.js). That test code would look like so:
/* app/controller/welcome.spec.js */
beforeEach(function() {
var app = angular.module("myApp", []); //module definition
require("./welcome")(app);
});
beforeEach(mockModule("myApp"));
describe("MyCtrl", () => {
var scope = {};
beforeEach(mockInject(function($controller) {
$controller("MyCtrl", {
$scope: scope
});
}));
it("has name in its scope", function() {
expect(scope.name).to.equal("not lebouf"); //the test will fail
});
});
Except, this is an angular controller we're testing and it's not that simple. We need the angular object itself. So lets set it up. I'll explain why it is done how it is done next:
/* test-setup.js */
const jsdom = require("jsdom").jsdom; //v5.6.1
const chai = require("chai");
global.document = jsdom("<html><head></head><body></body></html>", {});
global.window = document.defaultView;
global.window.mocha = true;
global.window.beforeEach = beforeEach;
global.window.afterEach = afterEach;
require("angular/angular");
require("angular-mocks");
global.angular = window.angular;
global.mockInject = angular.mock.inject;
global.mockModule = angular.mock.module;
global.expect = chai.expect;
console.log("ALL SET");
And we'll run the tests as:
node_modules/.bin/mocha ./init.js app/**/*.spec.js
#or preferably as `npm test` by copying the abev statement into package.json
extra info
Here is how init.js is setup as is:
jsdom: f you require("angular/angular") you'll see that it needs a window instance. jsdom can create documents and windows and so on without a web browser!
window.mocha: we need angular-mocks to populate our angular with the necessary utilities. But if you look at the code you'll notice that window.mocha || window.jasmine needs to be true. Thats whywindow.mocha = true`
window.beforeEach, window.afterEach: the same reason as above; because angular-mocks.js demands it.
I set some global variables that I plan to use commonly in my tests: angular, expect, mockInject, mockModule.
Also these may provide some additional information:
https://kasperlewau.github.io/post/angular-without-karma/
https://gist.github.com/rikukissa/dcb422eb3b464cc184ae
I'm trying for a week run karma in a project. I've follow this tutorial AngularJS Unit Test but when run karma start the console shows this error:
PhantomJS 2.1.1 (Linux 0.0.0) ERROR
ReferenceError: Can't find variable: angular
at /home/user/workspace/UnitTest/app/app.js:1
I thought the problem was in my project, so i've created a new one and the error persists.
My karma.conf.js is
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
files: [
'app/*.js',
'tests/*.js',
'node_modules/angular/angular.js',
'node_modules/angular/angular.min.js',
'node_modules/angular-mocks/angular-mocks.js'
],
exclude: [
],
preprocessors: {
},
reporters: ['progress'],
// web server port
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['PhantomJS'],
customLaunchers: {
Chrome_without_security: {
base: 'PhantomJS',
flags: ['--disable-web-security']
}
},
singleRun: false,
concurrency: Infinity
})
}
and app.js
angular.module('MyApp', [])
.filter('reverse',[function(){
return function(string){
return string.split('').reverse().join('');
}
}])
I've tried to change the node version too, but it isn't worked.
The solution was put the angular imports before the app files like this:
files: [
'node_modules/angular/angular.js',
'node_modules/angular/angular.min.js',
'node_modules/angular-mocks/angular-mocks.js',
'app/*.js',
'tests/*.js'
]
This is my first time using Jasmine, and I have tested my first Factory without problems.
But now, I want to test this Service:
angular.module('Questions', [])
.service('QuestionsService', function($uibModal, $log, _) {
...
}
$uibModal is from UI Bootstrap (see here) and _ is Lodash.
My Jasmine test so far is:
describe('Service: QuestionsService', function() {
var QuestionsService;
beforeEach(inject(function(_QuestionsService_) {
QuestionsService = _QuestionsService_;
}));
...
}
And when I try it (grunt test), I get the following error:
Error: [$injector:unpr] Unknown provider: $uibModalProvider <- $uibModal <- QuestionsService
And at some point I also had:
Error: [$injector:unpr] Unknown provider: _Provider <- _ <- QuestionsService
If it can help, my Karma conf is:
module.exports = function(config) {
'use strict';
config.set({
autoWatch: true,
basePath: '../',
frameworks: [
"jasmine"
],
// list of files / patterns to load in the browser
files: [
// bower:js
'bower_components/jquery/dist/jquery.js',
'bower_components/lodash/lodash.js',
'bower_components/angular/angular.js',
'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap.js',
'bower_components/angular-animate/angular-animate.js',
'bower_components/angular-cookies/angular-cookies.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-touch/angular-touch.js',
'bower_components/angular-bootstrap/ui-bootstrap-tpls.js',
'bower_components/angular-mocks/angular-mocks.js',
// endbower
"app/scripts/**/*.js",
"test/mock/**/*.js",
"test/spec/**/*.js",
],
exclude: [
],
port: 8080,
browsers: [
"PhantomJS"
],
plugins: [
"karma-phantomjs-launcher",
"karma-jasmine"
],
singleRun: false,
colors: true,
logLevel: config.LOG_INFO,
});
};
Just in case others find this. To solve the error when testing a directive's controller, I mocked the $uibModal service, conceptually like this:
describe('Service: QuestionsService', function() {
var controller;
beforeEach(inject(function($controller) {
controller = $controller('controllerName', {
$uibModal : {}
});
}));
...
}
$uibModal may need to be more than just an empty object if you are writing tests against controller functions that interact with it.
The app's module was not included in the test. The refactored test for the QuestionService would be:
describe('Service: QuestionsService', function() {
var QuestionsService;
// The module needs to be included in the test.
beforeEach(module('boardgameApp'));
beforeEach(inject(function(_QuestionsService_) {
QuestionsService = _QuestionsService_;
}));
...
}
I am using requirejs for my angularjs application. For TDD i am using mocha. As per this article, I am writing my test cases but there is always this error that comes while executing a test case
Error: [$injector:modulerr] Failed to instantiate module sampleapp due to:
Error: [$injector:nomod] Module 'sampleapp' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
Test Case:
define([
'angular',
'angular-mocks'
], function() {
describe('main controller todo app', function() {
var scope, ctrl;
beforeEach(module('sampleapp',[]));
beforeEach(inject(function($rootScope, $controller) {
scope = $rootScope.$new();
ctrl = $controller('mainCtrl', {$scope: scope});
}));
it('is todo added', function() {
scope.todo = 'My new Todo';
scope.addTodo();
assert.equal(scope.todos.length, 1);
});
})
});
Karma Conf:
module.exports = function(config) {
'use strict';
config.set({
basePath: './',
frameworks: [
'requirejs',
'mocha',
'chai'
],
files: [{
pattern: 'test/test-main.js',
watched: true
}, {
pattern: 'app/angular/**/*.js',
included: false
}, {
pattern: 'app/*.js',
included: false
}, {
pattern: 'app/scripts/additional/**/*.js',
included: false
}, {
pattern: 'test/spec/**/*.js',
included: false,
watched: true
}],
exclude: [
'app/main.js'
],
reporters: ['spec'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
captureTimeout: 20000,
singleRun: false,
plugins: [
'karma-chai',
'karma-mocha',
'karma-requirejs',
'karma-spec-reporter',
'karma-chrome-launcher'
]
});
}
Test Main:
var tests = [];
var TEST_REGEXP = /test[A-Za-z0-9]{1,}-[A-Za-z0-9]{1,}\.js/i;
Object.keys(window.__karma__.files).forEach(function(file) {
if (TEST_REGEXP.test(file)) {
tests.push(file);
}
});
requirejs.config({
'baseUrl': '/base/app',
'paths': {
'angular': 'scripts/additional/angular/angular',
'angular-mocks': 'scripts/additional/angular-mocks/angular-mocks',
},
'shim': {
'angular-mocks' : {'exports' : 'angular-mocks', 'deps': ['angular']}
},
'deps': tests,
'callback': window.__karma__.start
});
Any help or direction to fix this is greatly appreciated
the main problem was that the file where my module was getting created was not loaded (i.e. the file executing code var app = angular.module("sampleapp",[]);)
Once that was corrected everything started to work