Foundation-Apps angular site integration with karma-jasmine unit testing - javascript

I believe there is a problem with using angular-mocks and foundation-apps when trying to run a karma jasmine unit test. It could also be that I have missed something. Since there is so much code to see I have posted an example project on github for review.
Basically the site runs fine and karma runs the test but when you debug into the angular.mocks.module function you find that your module from your app is not being loaded.
If you take foundation-apps out of the situation it will work fine.
Could this be a version conflict because foundation-apps has an older dependency for angular-mocks?
fatest on github

I hit the same issue and my solution was to add resulting css-file (app.css - generated with sass task) to karma configuration. Without this file i got:
TypeError: 'null' is not an object (evaluating 'mediaQueries[key].replace')
Here is my gulp config:
var karma = require('karma').server;
//...........//
// Compiles Sass
gulp.task('sass', function () {
return gulp.src('client/assets/scss/app.scss')
.pipe(plugins.sass({
includePaths: paths.sass,
outputStyle: (isProduction ? 'compressed' : 'nested'),
errLogToConsole: true
}))
.pipe(plugins.autoprefixer({browsers: ['last 2 versions', 'ie 10']}))
.pipe(gulp.dest('./build/assets/css/'))
.pipe(plugins.livereload());
});
/// ..... some other things here ......///
gulp.task('unit-test', function (done) {
var testFiles = [
{pattern:'./build/assets/js/foundation.js',watched:false},
{pattern:'./build/assets/js/routes.js',watched:false},
{pattern:'./build/assets/css/app.css',watched:false},
{pattern:'./build/assets/js/templates.js',watched:false},
{pattern:'./bower_components/angular-mocks/angular-mocks.js', watched:false},
{pattern:'./client/assets/js/*.js'},
{pattern:'./client/templates/**/*.js'}
];
karma.start({
configFile:__dirname + '/karma.conf.js',
singleRun: true,
files: testFiles
}, done);
});
Assuming your application is already builded, just run gulp unit-test.

Related

UNKOWN error thrown when compiling typescript using Gulp in VS2015

I have installed Visual Studio 2015 (with no other previous versions) on a new laptop and have pulled down the source for our MVC web app. We have a gulp file with tasks to compile our less and typescript.
When running this task ...
cmd.exe /c gulp -b "C:\Code\Trunk\MyProj\MyProj.Web" --color --gulpfile "C:\Code\Trunk\MyProj\MyProj.Web\Gulpfile.js" typescript
... I get the following error:
[09:43:16] Using gulpfile C:\Code\Trunk\MyProj\MyProj.Web\Gulpfile.js
[09:43:16] Starting 'typescript'...
[09:43:34] Plumber found unhandled error:
Error: UNKNOWN, open 'C:\Code\Trunk\MyProj\MyProj.Web\app\allergy\main.js'
Process terminated with code 0.
Here is the task in the gulp file (with other parts removed for brevity):
var gulp = require("gulp");
var plumber = require("gulp-plumber");
var sourcemaps = require("gulp-sourcemaps");
var typescript = require("gulp-typescript");
var merge = require("merge2");
var paths = {
typescript: {
globpatterns: {
all: "./Scripts/**/*.ts",
excludedefinitions: "!./Scripts/**/*.d.ts"
}
}
};
gulp.task("typescript", function () {
var result = gulp.src([
paths.typescript.globpatterns.all,
paths.typescript.globpatterns.excludedefinitions
])
.pipe(plumber())
.pipe(sourcemaps.init())
.pipe(typescript({
removeComments: true,
declarationFiles: false,
noImplicitAny: false,
noEmitOnError: true,
module: "amd",
target: "ES5"
}));
return merge([
result.js.pipe(gulp.dest("./")),
result.pipe(sourcemaps.write()).pipe(gulp.dest("./"))
]);
});
My colleague has the same set-up as me and gets no error.
Typescript is set to version 1.0 in the project file (<TypeScriptToolsVersion>1.0</TypeScriptToolsVersion>) and I can't change this just now. I wondered if the reason was beacuse I don't have this version installed on my machine but my colleague doesn't either. C:\Program Files (x86)\Microsoft SDKs\TypeScript only has a folder for 1.7
I noticed that the task completes successfully if I remove either of the 2 lines with in the merge block.
It's a different .js file in the error message each time
I searched the web to see what the UNKNOWN error even means but couldn't find anything obvious / helpful. Anyone know how to fix this error? Or how I go about finding out why it's being thrown?
EDIT 20-Jan-2016
So, I was getting this error consistently for about a week ... and now it has stopped happening. I haven't made any changes to my development environment either. I'd like to leave this question open since I'm curious as to why this happened.

Running protractor config results 'This webpage is not available'

I'm trying to test protractor on a vanilla.js app and when I run protractor basicConf.js
I am getting below error :
This webpage is not available ERR_CONNECTION_REFUSED
This is my test:
describe('foo', function() {
beforeEach(function() {
browser.get('index.html');
});
it('should return the same result as browser.findElement', function() {
$('#newItem').sendKeys('sdg');
element('#addBtn').click().then(function(){
});
});
})
And my protractor config:
// The main suite of Protractor tests.
exports.config = {
seleniumAddress: 'http://localhost:4444/wd/hub',
framework: 'jasmine2',
// Spec patterns are relative to this directory.
specs: [
'spec.js'
],
// Exclude patterns are relative to this directory.
exclude: [
'basic/exclude*.js'
],
capabilities: {'browserName': 'chrome'},
baseUrl: 'http://localhost:' + ( '8082'),
jasmineNodeOpts: {
isVerbose: true,
realtimeFailure: true
},
params: {
login: {
user: 'Jane',
password: '1234'
}
}
};
Any ideas what I need to do to start fixing this?
I have run both:
protactor npm install -g protractor
webdriver webdriver-manager update
Error connection gets refused if either the webdriver server isn't started or there is a configuration compatibility issue with your protractor and browser. Looking at your config file and config data, there is no such issue. However, you should start your webdriver before running your tests. Open a command prompt in windows or terminal in mac and then run the following command to start the selenium webdriver -
webdriver-manager start
Later run your protractor scripts with the command that you already have. Hope this helps.
Looking over your test I believe the issue originates from the address that you are passing to the browser.get() function. You'll want to either reference the baseUrl you setup in the config file and append the "index.html" piece in your test or adjust the baseUrl and reference that in your beforeEach function. Try one of the following:
...
baseUrl: 'http://localhost:8082',
...
browser.get(browser.baseUrl + '/index.html');
or
...
baseUrl: 'http://localhost:8082/',
...
browser.get(browser.baseUrl);
or
browser.get('http://localhost:8082/index.html');
Also you could try this:
...
baseUrl: 'http://localhost:8082/index.html');
...
browser.get(browser.baseUrl);

How to execute jasmine tests for node modules from grunt

I want to run some Jasmine 2.x tests for node.js modules in a Grunt build. My setup looks like this:
src/foo.js
exports.bar = 23;
spec/foo.spec.js
var foo = require("../src/foo.js");
define("foo", function() {
it("exports bar as 23", function() {
expect(foo.bar).toBe(23);
});
});
With grunt-contrib-jasmine the node module system is not available and I get
>> ReferenceError: Can't find variable: require at
>> spec/foo.spec.js:1
There is grunt-jasmine-node, but it depends on jasmine-node which is unmaintained and includes Jasmine 1.3.1, so this is not an option.
Jasmine supports node.js out of the box, by including a file jasmine.json in the spec directory, I can run the tests with the jasmine cli. Is there any clean way to run the same tests from grunt as well?
You could use grunt-exec, which just executes the value as if typed on the command line:
module.exports = function (grunt) {
grunt.initConfig({
exec: {
jasmine: "jasmine"
},
env: {
test: {
NODE_ENV: "test"
}
}
});
grunt.loadNpmTasks("grunt-exec");
grunt.loadNpmTasks("grunt-env");
grunt.registerTask("test", [
"env:test",
"exec:jasmine"
]);
};
This will allow you to keep jasmine up to date as well as use it with other grunt tasks.

grunt jasmine-node tests are running twice

I set up grunt to run node.js jasmine tests. For some reason, with this config, the results always show double the tests.
Here is my config:
I'm using jasmine-node which plugs into grunt.
/spec/some-spec.js:
var myModule = require('../src/myModule.js');
describe('test', function(){
it('works', function(done){
setTimeout(function(){
expect(1).toBe(1);
done();
}, 100);
});
});
Gruntfile.js:
module.exports = function(grunt) {
grunt.initConfig({
jasmine_node: {
options: {
forceExit: true
},
all: ['spec/']
}
});
grunt.loadNpmTasks('grunt-jasmine-node');
grunt.registerTask('default', ['jasmine_node']);
};
This results in two tests running rather than one.
> grunt
Running "jasmine_node:all" (jasmine_node) task
..
Finished in 0.216 seconds
2 tests, 2 assertions, 0 failures, 0 skipped
I was able to reproduce the behavior. This is what seems to be happening:
The task looks in the specified folder (spec in your case) for files with spec in the name.
Then it looks again in every folder in the whole project for files with spec in the name.
What it ends up with is 2 overlapping sets of test files to run.
My first attempt at trying to coerce it into more logical behavior was to set specNameMatcher: null (default is 'spec'), and leave the folder set to 'spec/'. This results in no tests being run, since apparently both conditions (name and folder) must be met for files in the specified folder. You get the same problem if specNameMatcher is left at the default value, but the files in the folder don't have 'spec' in the name.
What does work is to set the folder (or 'test set' or whatever you want to call it) to []:
jasmine_node: {
options: {
forceExit: true
},
all: []
}
The catch is that if you have any other files somewhere else in the project with 'spec' in the name, they'll be mistaken for tests by jasmine.
I would consider this behavior a bug, and it should probably be reported via the project's github issues page.
This grunt plugin ( https://github.com/jasmine-contrib/grunt-jasmine-node ) seems to be dead ( https://github.com/jasmine-contrib/grunt-jasmine-node/issues/60 ).
Maybe it is a better to switch to https://github.com/onury/grunt-jasmine-nodejs ?
The jasmine-node project is pretty old. The latest commit is from July of 2014. The grunt-jasmine-node plugin appears to be active, but running against something that is going stale seems a little pointless IMHO.
To test CommonJS modules using Jasmine I'd recommend using Karma along with the
karma-jasmine and karma-commonjs plugins. I got your example working with the following files:
package.json
{
"private": "true",
"devDependencies": {
"grunt": "^0.4.5",
"grunt-jasmine-node": "^0.3.1",
"grunt-karma": "^0.10.1",
"jasmine-core": "^2.3.4",
"karma": "^0.12.31",
"karma-commonjs": "0.0.13",
"karma-jasmine": "^0.3.5",
"karma-phantomjs-launcher": "^0.1.4"
}
}
karma.conf.js
module.exports = function(config) {
config.set({
basePath: '.',
frameworks: ['jasmine', 'commonjs'],
files: [{
pattern: 'src/**/*.js'
}, {
pattern: 'spec/**/*.js'
}],
preprocessors: {
'src/**/*.js': ['commonjs'],
'spec/**/*.js': ['commonjs']
},
reporters: ['progress'],
browsers: ['PhantomJS']
});
};
Gruntfile.js (optional if you still want to use grunt)
module.exports = function(grunt) {
grunt.initConfig({
karma: {
unit: {
configFile: 'karma.conf.js',
options: {
singleRun: true
}
}
}
});
grunt.loadNpmTasks('grunt-karma');
grunt.registerTask('default', ['karma:unit']);
};
You should also install the karma command line runner globally, just like you probably did with grunt. npm install -g karma-cli
From your command line you can start karma by typing karma start. It will run the tests and then watch your files and re-run them on every save. (VERY NICE)
Alternatively you can run karma start --single-run to have it just run your tests once and exit. If you also updated your Gruntfile you can also just run grunt to run the tests once.
The current up voted answer isn't the solution. You simply modify the expression that's going to match your tests. The answer is as follows:
module.exports = function(grunt) {
grunt.initConfig({
jasmine_node: {
options: {
forceExit: true
},
all: ['spec/*spec.js']
}
});
grunt.loadNpmTasks('grunt-jasmine-node');
grunt.registerTask('default', ['jasmine_node']);
};
Here you can see that 'all' is set to *'spec/spec.js'. This will search for all tests.
Secondly, just because a project hasn't had a recently commit, doesn't mean it's "old". jasmine-node is simply stable.
I have the same issue using grunt-jasmine-node, and as aeryaguzov points out, that project is no longer maintained. Switching to grunt-jasmine-node-new solves the issue for me.
grunt-jasmine-node-new is a fork of grunt-jasmine-node that is actively maintained, and can be found here: https://www.npmjs.com/package/grunt-jasmine-node-new

ReferenceError: module is not defined - Karma/Jasmine configuration with Angular/Laravel app

I have an existing Angular/Laravel app in which Laravel acts as an API to the angular frontend serving only JSON data. The page that loads the angular app, index.php, is currently served by Laravel. From there, Angular takes over.
I'm have a very difficult time trying to get started with Karma/Jasmine. When running my tests using karma start or karma start karma.conf.js from the root directory of my project, I get the following error:
ReferenceError: module is not defined
Full output:
INFO [karma]: Karma v0.12.28 server started at http://localhost:9876/
INFO [launcher]: Starting browser Chrome
WARN [watcher]: Pattern "/Users/raph/coding/webroot/digitalocean/rugapp/public/rugapp/*.js" does not match any file.
INFO [Chrome 39.0.2171 (Mac OS X 10.9.5)]: Connected on socket 3OCUMp_xhrGtlGHwiosO with id 7897120
Chrome 39.0.2171 (Mac OS X 10.9.5) hello world encountered a declaration exception FAILED
ReferenceError: module is not defined
at Suite.<anonymous> (/Users/raph/coding/webroot/digitalocean/rugapp/tests/js/test.js:3:16)
at jasmineInterface.describe (/Users/raph/coding/webroot/digitalocean/rugapp/node_modules/karma-jasmine/lib/boot.js:59:18)
at /Users/raph/coding/webroot/digitalocean/rugapp/tests/js/test.js:1:1
Chrome 39.0.2171 (Mac OS X 10.9.5): Executed 2 of 2 (1 FAILED) (0.005 secs / 0.003 secs)
However, the chrome broswer does launch with the following displayed:
My karma.conf.js file is as follows:
// Karma configuration
// Generated on Mon Dec 22 2014 18:13:09 GMT-0500 (EST)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: 'public/rugapp/',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'*.html',
'**/*.js',
'../../tests/js/test.js',
'../../tests/js/angular/angular-mocks.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'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
});
};
My package.json file is shown below:
{
"devDependencies": {
"gulp": "^3.8.8",
"karma": "^0.12.28",
"karma-chrome-launcher": "^0.1.7",
"karma-jasmine": "^0.3.2",
"laravel-elixir": "*"
}
}
test.js
describe("hello world", function() {
var CreateInvoiceController;
beforeEach(module("MobileAngularUiExamples"));
beforeEach(inject(function($controller) {
CreateInvoiceController = $controller("CreateInvoiceController");
}));
describe("CreateInvoiceController", function() {
it("Should say hello", function() {
expect(CreateInvoiceController.message).toBe("Hello");
});
});
});
describe("true", function() {
it("Should be true", function() {
expect(true).toBeTruthy();
});
});
Any help would be greatly appreciated.
Perhaps this will help someone.
The solution, for me, was to make sure angular-mocks.js was loaded before my tests. If you're not sure, you control the order in karma.conf.js under the following section:
// list of files / patterns to load in the browser
files: [
// include files / patterns here
Next, to get my test to actually load my angular app, I had to do the following:
describe("hello world", function() {
var $rootScope;
var $controller;
beforeEach(module("YourAppNameHere"));
beforeEach(inject(function($injector) {
$rootScope = $injector.get('$rootScope');
$controller = $injector.get('$controller');
$scope = $rootScope.$new();
}));
beforeEach(inject(function($controller) {
YourControllerHere = $controller("YourControllerHere");
}));
it("Should say hello", function() {
expect(YourControllerHere.message).toBe("Hello");
});
});
And in your controller,
app.controller('YourControllerHere', function() {
this.message = "Hello";
});
Also, another way:
describe("YourControllerHere", function() {
var $scope;
var controller;
beforeEach(function() {
module("YourAppNameHere");
inject(function(_$rootScope_, $controller) {
$scope = _$rootScope_.$new();
controller = $controller("YourControllerHere", {$scope: $scope});
});
});
it("Should say hello", function() {
expect(controller.message).toBe("Hello");
});
});
Enjoy testing!
The error means angular was not able to inject your module. Most of the time this happens because of missing reference to script files. In this case, make sure to have all your script file is defined under [files] configuration of karma. Pay special attention to paths because if your script folder has nested structure, make sure to list as such. For example:
Scripts/Controllers/One/1.js
Scripts/Controllers/One/2.js
can be listed as in karma.conf.js>files as :
Scripts/Controllers/**/*.js
Just leave this here for future searchers.
If you are running angular unit tests in the browser directly without Karma (or in plunkr or jsfiddle ect...) Then it may be that
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.0/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.0/angular-route.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.0/angular-cookies.js"></script>
<!-- The Mocha Setup goes BETWEEN angular and angular-mocks -->
<script>
mocha.setup({
"ui": "bdd",
"reporter": "html"
});
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.0/angular-mocks.js"></script>
<script src="myApp.js"></script>
<script src="myTest.js"></script> <!-- test is last -->
The Mocha Setup goes BETWEEN angular and angular-mocks
I encountered a similar message and turned out I got my angular-mocks file path wrong. I used npm to install angular and angular-mocks, and I specified their path wrongly in my Karma.conf.js like this:
files: [
'node_modules/angular/angular.js',
'node_modules/angular/angular-mocks.js',
'scripts/*.js',
'tests/*.js'
],
I should specify the path of angular-mocks.js as this:
'node_modules/angular-mocks/angular-mocks.js'
Very simple error, but could be time-consuming to locate if you just started with AngularJS unit testing and didn't know where to look.

Categories

Resources