ReferenceError: Can't find variable: module in angular testing - javascript

I'm trying to write a test for my Angular controller, I'm using jasmine karma and angular-mocks, but keeps on getting the error ReferenceError: Can't find variable: module.
I had a bit of a search, but I already have the angular-mocks in my bower.
What could I be missing here?
The following is my code:
#controller
angular.module('cook_book_ctrl', [])
.controller('cookBookCtrl', function($scope, CookBook, CookBookRecipesService){
$scope.cookbookoptions = true;
CookBook.list()
.success(function(data){
$scope.recipeList = data;
CookBookRecipesService.loadCookBookRecipes($scope.recipeList);
})
.error(function(error){
})
});
#controller test
describe('CookBook controller spec', function(){
var $httpBackend, $rootScope, createController, authRequestHandler
beforeEach(module('cook_book_ctrl'));
})
#bower.json
{
"name": "HelloIonic",
"private": "true",
"devDependencies": {
"ionic": "driftyco/ionic-bower#1.0.0",
"ionic-service-analytics": "master",
"ionic-service-core": "~0.1.4",
"angular-mocks": "1.3.13"
},
"dependencies": {
"ng-cordova-oauth": "~0.1.2",
"ng-tags-input": "~2.3.0",
"angular": "~1.4.0",
"underscore": "~1.8.3",
"materialize": "~0.97.0"
},
"resolutions": {
"angular": "~1.4.0"
}
}
beforeEach(module('cook_book_ctrl'));
})
UPDATE: Screenshot added for clarity

Besides installing angular-mocks through bower, remember to add reference to angular-mocks.js in your karma config file, like below
config.set({
basePath: '../',
port: '8000',
files: [
'bower_components/angular/angular.js',
'bower_components/angular-mocks/angular-mocks.js',
...
]

In my case it was also about wrong order of files path in karma.conf.js.
Was:
// list of files / patterns to load in the browser
files: [
'tests/*.test.js', // this should not be as first!
'bower_components/angular/angular.min.js',
'bower_components/angular-mocks/angular-mocks.js',
'app/*.js',
],
Should be:
// list of files / patterns to load in the browser
files: [
'bower_components/angular/angular.min.js',
'bower_components/angular-mocks/angular-mocks.js',
'app/*.js',
'tests/*.test.js' // now it's cool
],
Maybe obvious thing or maybe not? ;-)

Related

Karma not running tests that have "import" statements in karma-webpack

I have some test files with tests I'd like to run against my app.
I am attempting to use karma, karma-webpack, karma-babel-preprocessor, karma-chrome-launcher, and jasmine in my testing. My app depends on many things, including backbone, marionette, etc. My app is built using webpack, and I am attempting to use webpack to bundle my files together for testing. (I initially wanted to see if I could skip this step, i.e. simply import a file to be tested, but it seems this is impossible.)
My test script looks like
package.json (scripts section)
"test": "./node_modules/karma/bin/karma start",
The rest of the files:
karma.conf.js
var webpackConfig = require('./config/webpack/webpack.test.conf.js');
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
files: [
{ pattern: 'test/**/*.spec.js', watched: true },
{ pattern: 'test/*.spec.js', watched: true }
],
exclude: [
],
preprocessors: {
'test/**/*.spec.js': ['webpack'],
'test/*.spec.js': ['webpack']
},
webpack: webpackConfig,
webpackMiddleware: {
stats: 'errors-only'
},
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
concurrency: Infinity
})
}
test/test.spec.js This file is seen
describe("A suite", function () {
it("contains spec with an expectation", function () {
expect(true).toBe(true);
});
});
describe("Another suite", function () {
it("contains another spec with an expectation", function () {
expect(true).toBe(false);
});
});
test/models/devicegroup.spec.js This file is not seen
import backbone from 'backbone';
describe("backbone", function () {
it("containsasdfasdfasdfasdfspec with an expectation", function ()
{
expect(true).toBe(false);
});
});
My folder structure is:
- karma.conf.js
- test/
- - test.spec.js
- - models/
- - - devicegroup.spec.js
- public/
- - js/
- - - app.js
When my files don't have import statements at the top, karma will run and pass/fail as expected. Putting an import statement at the top will cause karma to ignore the file. No errors are thrown.
How can I make karma / karma-webpack run my tests that have import statements / what is the karma-safe way to import modules into my tests?
When test/models/devicegroup.spec.js does not have an import statement:
// import backbone from 'backbone';
describe("backbone", function () {
it("contains with an expectation", function () {
expect(true).toBe(false);
});
});
the terminal output is: (notice one less test is run)
When test/models/devicegroup.spec.js does have an import statement:
import backbone from 'backbone';
describe("backbone", function () {
it("contains with an expectation", function () {
expect(true).toBe(false);
});
});
the terminal output is:
I see no errors in the browser Karma opens.
EDIT:
I have experimented by adding my source files to the files and preprocessors attributes in my karma.conf.js file, as per this repo example. There was no change in behavior other than a massively increased testing time.
karma.conf.js
files: [
{ pattern: 'public/js/**/*.js', watched: true},
{ pattern: 'test/**/*.spec.js', watched: true },
// each file acts as entry point for the webpack configuration
],
preprocessors: {
// add webpack as preprocessor
'public/js/**/*.js': ['webpack'],
'test/**/*.spec.js': ['webpack'],
},
EDIT2:
For the sake of experimentation (and based off this person's struggles), I have tried the above karma.conf.js in every possible combination - only test files in files and preprocessors, only source files, test files in one but not the other, source files in one but not the other, none, both. No good results, though occasionally new errors.
Little late, but I ran into the same problem, and was searching for hours, why my imports prevent the test suite from being executed. karma-webpack-4.0.0-rc.2 brought the enlightenment by providing error messages!!
I my case a couple of modules where not found, angular-mock, jquery, angular and more.
How to fix
Put there modules into the files array in your karma.config like:
files = [
"node_modules/jquery/dist/jquery.js",
"node_modules/angular/angular.js",
"node_modules/angular-mocks/angular-mocks.js",
{ pattern: "test/**/*.ts", watched: false }
I hope, this helps someone.
EDIT
My current versions of the testing related packages:
"#types/jasmine": "^2.8.8",
"jasmine": "^3.2.0",
"jasmine-core": "^3.2.1",
"jasmine-reporters": "2.3.2",
"jasmine-ts": "^0.2.1",
"karma": "3.0.0",
"karma-chrome-launcher": "2.2.0",
"karma-jasmine": "1.1.2",
"karma-junit-reporter": "1.2.0",
"karma-phantomjs-launcher": "1.0.4",
"karma-sourcemap-loader": "^0.3.7",
"karma-spec-reporter": "0.0.32",
"karma-webpack": "^4.0.0-rc.2",
"typescript": "3.0.3",
"webpack": "4.17.2",
"webpack-cli": "^3.1.0",
"webpack-dev-server": "3.1.8"

Grunt not defined

I am new to Grunt and have been struggling all day to make this work:
This is my Gulpfile.js:
'use strict';
// Time how long tasks take. Can help when optimizing build times
require('time-grunt')(grunt);
// Automatically load required Grunt tasks
require('jit-grunt')(grunt);
module.exports = function(grunt) {
// Define the configuration for all the tasks
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
// Make sure code styles are up to par and there are no obvious mistakes
jshint: {
options: {
jshintrc: '.jshintrc',
reporter: require('jshint-stylish')
},
all: {
src: [
'Gruntfile.js',
'app/scripts/{,*/}*.js'
]
}
}
});
grunt.registerTask('build', [
'jshint'
]);
grunt.registerTask('default', ['build']);
};
This my package.json:
{
"name": "conFusion",
"private": true,
"devDependencies": {
"grunt": "^1.0.1",
"grunt-contrib-jshint": "^1.0.0",
"jit-grunt": "^0.10.0",
"jshint-stylish": "^2.2.1",
"time-grunt": "^1.4.0"
},
"engines": {
"node": ">=0.10.0"
}
}
And this is the error message i get:
grunt build
Loading "Gruntfile.js"
tasks...ERROR >>
ReferenceError: grunt is not defined
Warning: Task "build" not found.Use--force to continue.
Aborted due to warnings.
Pls guys, I need help. I am working on windows 10, so am using the command line there.
module.exports = function(grunt) {
That is where you define a grunt variable. It is an argument to the function you created.
But you try to use it here:
require('time-grunt')(grunt);
and here:
require('jit-grunt')(grunt);
This is outside the function where the variable does not exist.
Move those lines inside the function.

Error: $injector:modulerr Module Error on running the application?

I am getting an angular module error whenever I am trying to inject dependencies using require.js
My bower.json file :
{
"name": "asa",
"version": "1.0",
"authors": [
"asda"
],
"description": "aaaa",
"dependencies": {
"angular": "1.3.8",
"angular-route": "1.3.8",
"requirejs": "2.1.15",
},
"license": "sss",
"homepage": "index.html",
"ignore": [
"**/.*",
"node_modules",
"bower_components",
"src/main/webapp/resources/bower_components",
"test",
"tests"
]
}
Main.js
var app = angular.module('myApp', ['route']);
app.service('abc', function () {
//some content
});
app.service('def', function( $http, $q ) {
//some content
});
var zzz = app.controller('zzz', function ($scope, $http, $filter, abc, def) {
//controller content
});
zzz.$inject = ['$scope', '$filter','abc','def'];
my data-main file containing the dependencies : main-di.js
require.config({
paths: {
angular: '../lib/dependencies/bower_components/angular/angular',
route: '../lib/dependencies/bower_components/angular-route/angular-route',
myApp: "person"
},
shim: {
angular: {
exports: "angular"
},
route: {
deps: ['angular']
},
myApp: {
deps: [ 'angular', 'route']
}
}
});
require(['myApp'], function () {
angular.bootstrap(document.getElementById('myApp'), ['myApp']);
});
On running the application i get the following error-
Error :
TypeError: e is undefined
...a("$ngControllerController",f));w(a)}}}n=e.module("ngRoute", ["ng"]).provider("$r...
Error: [$injector:modulerr] Failed to instantiate module myApp due to:
[$injector:nomod] Module 'myApp' 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.
http://errors.angularjs.org/1.3.8/$injector/nomod?p0=myApp minErr/<#http://localhost:8080/AngularJsInJava/lib/dependencies/bower_components/angular/angular.js:63:12
Can anybody please help me as to why I am getting this error??
This is not correct way to define controller.
var zzz = app.controller('zzz', function ($scope, $http, $filter, abc, def) {
//controller content
});
Create controller this way..
app.controller('zzz', ZzzCtrl);
ZzzCtrl.$inject = ['$scope', '$filter','abc','def'];
function ZzzCtrl ($scope, $filter, abc, def) {
// controller code here
}
Also if you use minification for your angular Code, you should always use annotations or "$inject"s . Not with controllers only.
eg.
angular.module('someModule').service('someService',['$someInjection', function($someInjection){}])

Setting up Karma with Browserify to test React (ES6) components

I'm having trouble setting up a test config with Karma + Browserify for some React components. Mentioning code is written in ES6 and I've upgraded to latest Babel version (6+), which I assume is the root of all evil in this config.
Since Babel is now split and has this plugin-based approach (presets), I'm not sure how I should specify this in the karma.conf file.
My current config looks like this:
module.exports = function(config) {
config.set({
basePath: '',
browsers: ['PhantomJS'],
frameworks: ['browserify', 'jasmine'],
files: [
'app/js/**/*',
'app/__tests__/**/*'
],
preprocessors: {
'app/js/**/*': ['browserify'],
'app/__tests__/**/*': ['browserify']
},
browserify: {
debug: true,
transform: ['babelify']
},
singleRun: true
});
};
However this fails with a bundle error (Unexpected token while parsing file...). Also I get You need to include some adapter that implements __karma__.start method! error message.
It's funny that this happens for some very simple components.
Eg simple React file:
import React from 'react';
class FooterComponent extends React.Component {
render() {
return (
<footer>
This is the application's footer
</footer>
);
}
}
export default FooterComponent;
And the test file doesn't even import it. It's just an always passing test like:
describe('Testing `Footer` component.', () => {
describe('Method: none', function() {
it('Should be a passing test', function() {
expect(true).toBe(true);
});
});
});
The Babel/Browserify related packages in package.json are:
{
"babel-preset-es2015": "^6.0.15",
"babel-preset-react": "^6.0.15",
"babelify": "^7.2.0",
"browserify": "^12.0.1",
}
Any ideas are appreciated. Especially since this used to work before upgrading to Babel 6+.
Cheers!
Add a .babelrc file to your root directory:
{
presets: ['es2015', 'react']
}

Browserify Shim Buffer core module

I'm trying to browserify my library where there are Buffer core module being use in different places.
I want to shim this core Buffer with another library that we are using.
I have tried to look into https://github.com/thlorenz/browserify-shim where I can specify my module that I want to shim but it doesn't seem to work.
I've created file called shim.js
var Buffer = require('myModule').Buffer;
module.exports = {
Buffer: { exports: Buffer }
};
in Package.json
{
...
"dependencies": {
"MD5": "^1.2.1",
"browser-request": "^0.3.1",
"browserify-shim": "^3.6.0",
...
},
"devDependencies": {
...
},
"browserify-shim": "./shims.js"
}
And in Gruntfile.js (I'm using grunt-browserify)
browserify: {
src: "./index.js",
options: {
transform: ['browserify-shim'],
browserifyOptions: {
builtins: false
},
bundleOptions: {
standalone: "mylibrary"
}
}
}
},
Right now when I grunt build the file I'm still seeing this being require in:
[function(_dereq_,module,exports){
(function (Buffer){
And in my browser is complaining about
Uncaught Error: Module name "buffer" has not been loaded yet for context: _. Use require([])

Categories