Protractor Angularjs E2E "browser is not a function" - angularjs

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.

Related

AngularJS Karma Jamsine Dependency Injection Error: Test Error: [$injector:unpr] Unknown provider: $mdDialogProvider <- $mdDialog

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?

"Error: [$injector:modulerr] Failed to instantiate module ng due" to while running karma test runner

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",

Angular Unit testing : $location in HTML5 mode requires a </path/to/my/app> tag to be present

I am using Karma to write my test scripts and here is my karma.conf.js code
'use strict';
/**
* Module dependencies.
*/
var _ = require('lodash'),
karmaReporters = ['spec', 'coverage'];
//Karma configuration
module.exports = function (karmaConfig) {
karmaConfig.set({
preprocessors: {
'./index.html': ['ng-html2js'],
'./app/*/modules/*/views/**/*.html': ['ng-html2js'],
'./app/config.js': ['coverage'],
'./app/application.js': ['coverage'],
'./app/*/modules/*/client/*.js': ['coverage'],
'./app/*/modules/*/client/config/*.js': ['coverage'],
'./app/*/modules/*/client/controllers/*.js': ['coverage'],
'./app/*/modules/*/client/directives/*.js': ['coverage'],
'./app/*/modules/*/client/services/*.js': ['coverage']
},
ngHtml2JsPreprocessor: {
moduleName: 'myApp',
cacheIdFromPath: function (filepath) {
return filepath;
}
},
// List of files / patterns to load in the browser
files: [
'./public/libs/angular/angular.js',
'./public/libs/angular-mocks/angular-mocks.js',
'./public/libs/angular-animate/angular-animate.js',
'./public/libs/angular-cookies/angular-cookies.js',
'./public/libs/angular-resource/angular-resource.js',
'./public/libs/angular-route/angular-route.js',
'./public/libs/angular-sanitize/angular-sanitize.js',
'./public/libs/angular-ui-router/release/angular-ui-router.js',
'./public/constants/constants.js',
'./app/config.js',
'./app/application.js',
'./app/*/modules/*/client/*.js',
'./app/*/modules/*/client/**/*.js',
'./app/*/modules/*/tests/unit/*.js',
'./index.html',
'./app/*/modules/*/client/views/**/*.html'
],
basePath: './',
//frameworks to use
frameworks: ['jasmine'],
// Test results reporter to use
// Possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
reporters: karmaReporters,
// Configure the coverage reporter
coverageReporter: {
dir: './coverage/client',
reporters: [
// Reporters not supporting the `file` property
{type: 'html', subdir: 'report-html'},
{type: 'lcov', subdir: 'report-lcov'},
// Output coverage to console
{type: 'text'}
],
instrumenterOptions: {
istanbul: {noCompact: true}
}
},
// Level of logging
// Possible values: karmaConfig.LOG_DISABLE || karmaConfig.LOG_ERROR || karmaConfig.LOG_WARN ||
// karmaConfig.LOG_INFO || karmaConfig.LOG_DEBUG
logLevel: karmaConfig.LOG_INFO,
browsers: ['Chrome'],
autoWatch: true,
singleRun: true,
colors: true
});
};
As per I remember it was working fine for certain time and due to some changes I am getting this error suddenly and I couldn't figure out what could be the issue.
Uncaught Error: [$location:no/path/to/my/app] $location in HTML5 mode requires a </path/to/my/app> tag to be present!
I have base url defined in my index file but still I am getting this error while running test scripts

Unit testing angular service with Karma in typescript : issue with inject

I have a very simple test where I inject $http $q and $httpBackend then do nothing (yet).
It crashs on the inject and I cannot figure out why.
Here's my code :
/// <reference path="../references.spec.ts" />
module Home.Test {
"use strict";
beforeEach(angular.mock.module("homeApp"));
describe("appInstanceService", () => {
let $httpBackend: angular.IHttpBackendService;
let $q: angular.IQService;
let service: Service.AppInstanceService;
beforeEach(
angular.mock.inject((
$http: angular.IHttpService,
_$q_: angular.IQService,
_$httpBackend_: angular.IHttpBackendService
) => {
$httpBackend = _$httpBackend_;
$q = _$q_;
service = new Service.AppInstanceService($http, $q, _, moment);
})
);
it("shoul pass", () => {
expect(true).toBe(true);
});
});
}
Here is my karma conf
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: [
'./bower_components/angular/angular.js',
'./bower_components/angular-animate/angular-animate.min.js',
'./bower_components/angular-bootstrap/ui-bootstrap-tpls.min.js',
'./bower_components/angular-mocks/angular-mocks.js',
'./bower_components/angular-sanitize/angular-sanitize.min.js',
'./bower_components/angular-translate/angular-translate.min.js',
'./bower_components/angular-ui-router/release/angular-ui-router.js',
'./bower_components/ui-select/dist/select.min.js',
'./bower_components/lucca-ui/dist/custom/lucca-ui-spe.js',
'./bower_components/moment/min/moment-with-locales.min.js',
'./bower_components/underscore/underscore-min.js',
'./dist/home.js',
'./tests/**/*.js',
],
preprocessors: {
'dist/home.js': ['coverage'],
},
// ngHtml2JsPreprocessor: {
// prependPrefix: '/web/Timmi.web/areas/timmi/'
// },
// list of files / patterns to exclude
exclude: [],
// web server port
port: 9876,
// 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: true,
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false,
plugins: [
'karma-jasmine',
// 'karma-chrome-launcher',
// 'karma-firefox-launcher',
// 'karma-ie-launcher',
'karma-phantomjs-launcher',
'karma-junit-reporter',
'karma-coverage',
// 'karma-ng-html2js-preprocessor'
],
browsers: ['PhantomJS'],
reporters: ['progress'],
junitReporter: {
outputFile: 'test-karma-results.xml',
suite: 'Lucca',
useBrowserName: false
},
coverageReporter: {
type : 'json',
dir : 'coverage/',
subdir: '.',
file : 'coverage-final.json'
}
});
};
And here is the error message I get in the console
Some bower_components were missing under the files section of my karma conf ...

jquery-jasmine unable to load json files

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/',
}

Resources