MSSQL - Nodejs - Undefined is not a function issue - sql-server

I have been trying to connect to MSSQL database using node module in my protractor tests. I tried both the methods below but each time I am either getting undefined is not a function or getting cannot read property of "query/execute".
Error: [launcher] Running 1 instances of WebDriver
[launcher] Error: TypeError: undefined is not a function
at exports.config.onPrepare (....\conf\Conf.js:39:28)
I have my connection defined in conf.js
var HtmlReporter = require('protractor-html-screenshot-reporter');
var mysql = require('../node_modules/mssql');
exports.config = {
seleniumAddress: 'http://localhost:4444/wd/hub', //desktop
allScriptsTimeout: 40000,
baseUrl: 'https://myurl.com/#/',
// frameworks to use
frameworks: 'jasmine',
//Capabilities to be passed to the webdriver instance.
multiCapabilities: [{
'browserName': 'chrome'
// }, {
// 'browserName': 'firefox'
//},
// {
// 'browserName': 'internet explorer'
}],
// Spec patterns are relative to the current working directory.
specs: [
'../tests/HomePage.js'
],
onPrepare: function() {
var sql = require('mssql/');
var config = {
server : '*****',
user : 'myusername',
password : 'pass',
database: 'mydb'
};
browser.driver.manage().window().maximize();
jasmine.getEnv().addReporter(new HtmlReporter({
baseDirectory: '/MyDirectory/screenshots'
}));
},
jasmineNodeOpts: {
showColors: true
}
};
In my Test, I did the following: test.js
describe ( " page test , function() {
it('Should add customer', function() {
blah blah....
});//This click will create a record in the backend
// I am attempting to get the record:
function runQuery() {
var connection = new sql.Connection(config, function(err) {
var request = new sql.Request(connection); // or: var request = connection.request();
request.query('select top 1 as result from customers', function(err, recordset) {
// ... error checks
console.log("this is the request: " + request);
console.dir(recordset);
});
});
};

I used dqlserver unofficial and it worked pretty well. We use Windows authentication to login to MSSQL studio so use the below.
var sql = require('node-sqlserver-unofficial');
var conn_str = "Driver={SQL Server Native Client 11.0};Server={your server};Database={your database};Trusted_Connection={Yes}";
sql.open(conn_str, function (err, conn) {
if (err) {
console.log("Error opening the connection!");
return;
}
conn.queryRaw("SELECT TOP 10 * FROM Employee", function (err, results) {
if (err) {
console.log("Error running query!");
return;
}
for (var i = 0; i < results.rows.length; i++) {
console.log("\n")
console.log("Record Info: ");
for (var j = 0; j < results.rows.length; j++) {
console.log(results.rows[i][j]);
}
}
});
});
Download MSSQL Unofficial package from here:
https://www.npmjs.com/package/node-sqlserver-unofficial

Related

Crash protractor on Chrome

I am experiencing problems when running the following script on a specific site. The script works on firefox but on chrome it crashes with the following stacktrace:
Protractor.waitForAngular() - Locator: By(css selector, *[id="loading-app-content"])
at WebDriver.schedule (/usr/local/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/webdriver.js:377:17)
at ProtractorBrowser.executeAsyncScript_ (/usr/local/lib/node_modules/protractor/built/browser.js:232:28)
at runWaitForAngularScript (/usr/local/lib/node_modules/protractor/built/browser.js:263:30)
at ProtractorBrowser.waitForAngular (/usr/local/lib/node_modules/protractor/built/browser.js:266:16)
at ElementArrayFinder.getWebElements (/usr/local/lib/node_modules/protractor/built/element.js:154:29)
at ElementFinder.isPresent (/usr/local/lib/node_modules/protractor/built/element.js:904:46)
at /usr/local/lib/node_modules/protractor/built/expectedConditions.js:86:20
at /usr/local/lib/node_modules/protractor/built/expectedConditions.js:63:20
at /usr/local/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/webdriver.js:716:14
at TaskQueue.execute_ (/usr/local/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/promise.js:2913:14)
My protractor-conf.js
exports.config = {
seleniumAddress: 'http://localhost:4444/wd/hub', // This is targetting your local running instance of the selenium webdriver
specs: [
'./features/**/*.feature'
],
capabilities: {
browserName: 'chrome',
},
framework: 'custom',
frameworkPath: require.resolve('protractor-cucumber-framework'), // Here it is
cucumberOpts: {
format: 'pretty',
require: './features/step_definitions/**/*.js' // This is where we'll be writing our actual tests
},
allScriptsTimeout: 11000,
onPrepare: function() {
browser.driver.manage().window().setSize(1400, 900);
browser.driver.manage().window().maximize();
},
useAllAngular2AppRoots: true
};
The test:
test = function() {
var EC = protractor.ExpectedConditions;
var el= element(by.className("preview-toggle"));
this.Given(/^I open up the application$/, function (callback) {
browser.get('foo.com').then(callback);
});
this.When(/^I click on add$/, function (callback) {
// Write code here that turns the phrase above into concrete actions
browser.wait(EC.invisibilityOf(element(by.id("loading-app-content"))), 30000).then(function () {
browser.wait(EC.presenceOf(element(by.css(".preview-toggle"))), 30000).then(function () {
browser.wait(EC.visibilityOf(element(by.css(".preview-toggle"))), 30000).then(function () {
browser.wait(EC.elementToBeClickable(element(by.css(".preview-toggle"))), 30000).then(function () {
el.click().then(callback);
});
});
});
});
});
this.Then(/^I should be the best$/, function (callback) {
callback();
});
};
module.exports=test;
Thing is every actions I do (even clicking on body) gives this error. Any other angular page works in chrome.
My specfic question is: what is causing chrome to crash?

setting proxy or backend URL while doing gulp build:dist

We have some code in Angular JS which is build using gulp (babel).
We have necessity to redirect the api service calls to a different server.
Hence, which development we run gulp server and with that add the api-host server in the proxy argument while running gulp server, as follows:
gulp serve:dist --mock no --proxy http://<host-name>:8090
Now, after development, we build and distribute the same bundle to different host (not the same host where the api services are hosted). Now we are not able to connect to the api server. The command we use to build is
gulp build:dist --mock no
Even if we add the proxy argument here, it doesn't works.
gulp build:dist --mock no --proxy http://<host-name>:8090
We tried customizing the "gulpfile.babel.js" file. but no result.
The following is the "gulpfile.babel.js" used:
'use strict';
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var runSequence = require('run-sequence');
var del = require('del');
var _ = require('lodash');
var historyApiFallback = require('connect-history-api-fallback');
var path = require('path');
var args = require('yargs').argv;
var proxyMiddleware = require('http-proxy-middleware');
var merge = require('merge-stream');
// browserSync
var browserSync = require('browser-sync');
var reload = browserSync.reload;
// config & testing
var config = require('./build/build.config.js');
var protractorConfig = require('./build/protractor.config.js');
var karmaConfig = require('./build/karma.config.js');
var KarmaServer = require('karma').Server;
var pkg = require('./package');
/* jshint camelcase:false*/
var webdriverStandalone = require('gulp-protractor').webdriver_standalone;
var webdriverUpdate = require('gulp-protractor').webdriver_update;
//update webdriver if necessary, this task will be used by e2e task
gulp.task('webdriver:update', webdriverUpdate);
// util functions
function sortModulesFirst(a, b) {
var module = /\.module\.js$/;
var aMod = module.test(a.path);
var bMod = module.test(b.path);
// inject *.module.js first
if (aMod === bMod) {
// either both modules or both non-modules, so just sort normally
if (a.path < b.path) {
return -1;
}
if (a.path > b.path) {
return 1;
}
return 0;
} else {
return (aMod ? -1 : 1);
}
}
// serve app in dev mode or prod mode
function serverOptions(logPrefix) {
var proxy = args.proxy;
var options = {
notify: false,
logPrefix: pkg.name,
server: {
baseDir: ['build', 'client']
}
};
// use a proxy server to serve '/api/**'' and '/auth' routes
if (proxy && args.mock === 'no') {
options.server.middleware = [
proxyMiddleware(['/auth', '/api'], {
target: proxy
}),
historyApiFallback()
];
} else {
// use Angular's $httpBackend as the server
options.server.middleware = [
historyApiFallback()
];
}
if (logPrefix) {
options.logPrefix = pkg.name;
}
return options;
}
// run unit tests and watch files
gulp.task('tdd', function(cb) {
new KarmaServer(_.assign({}, karmaConfig, {
singleRun: false,
action: 'watch',
browsers: ['PhantomJS']
}), cb).start();
});
// run unit tests with travis CI
gulp.task('travis', ['build'], function(cb) {
new KarmaServer(_.assign({}, karmaConfig, {
singleRun: true,
browsers: ['PhantomJS']
}), cb).start();
});
// optimize images and put them in the dist folder
gulp.task('images', function() {
return gulp.src(config.images, {
base: config.base
})
.pipe($.imagemin({
progressive: true,
interlaced: true
}))
.pipe(gulp.dest(config.dist))
.pipe($.size({
title: 'images'
}));
});
//generate angular templates using html2js
gulp.task('templates', function() {
return gulp.src(config.tpl)
.pipe($.changed(config.tmp))
.pipe($.html2js({
outputModuleName: 'templates',
base: 'client',
useStrict: true
}))
.pipe($.concat('templates.js'))
.pipe(gulp.dest(config.tmp))
.pipe($.size({
title: 'templates'
}));
});
//generate css files from scss sources
gulp.task('sass', function() {
return gulp.src(config.mainScss)
.pipe($.sass())
.pipe($.autoprefixer({
browsers: ['last 2 versions'],
cascade: false
}))
.on('error', $.sass.logError)
.pipe(gulp.dest(config.tmp))
.pipe($.size({
title: 'sass'
}));
});
//generate a minified css files, 2 js file, change theirs name to be unique, and generate sourcemaps
gulp.task('html', function() {
let useminConfig = {
path: '{build,client}',
css: [$.csso(), $.rev()],
vendorJs: [$.uglify({
mangle: false
}), $.rev()],
mainJs: [$.ngAnnotate(), $.uglify({
mangle: false
}), $.rev()]
};
if (args.mock === 'no') {
// Don't include mock vendor js
useminConfig.mockVendorJs = [];
return gulp.src(config.index)
.pipe($.usemin(useminConfig))
.pipe($.replace('<script src="assets/js/mock-vendor.js"></script>', ''))
.pipe(gulp.dest(config.dist))
.pipe($.size({
title: 'html'
}));
} else {
// Include mock vendor js
useminConfig.mockVendorJs = [$.uglify({
mangle: false
}), $.rev()];
return gulp.src(config.index)
.pipe($.usemin(useminConfig))
.pipe(gulp.dest(config.dist))
.pipe($.size({
title: 'html'
}));
}
});
// clean up mock vendor js
gulp.task('clean:mock', function(cb) {
if (args.mock === 'no') {
let paths = [path.join(config.dist, 'assets/js/mock-vendor.js')];
del(paths).then(() => {
cb();
});
} else {
cb();
}
});
//copy assets in dist folder
gulp.task('copy:assets', function() {
return gulp.src(config.assets, {
dot: true,
base: config.base
})
//.pipe(gulp.dest(config.dist + '/assets'))
.pipe(gulp.dest(config.dist))
.pipe($.size({
title: 'copy:assets'
}));
});
//copy assets in dist folder
gulp.task('copy', function() {
return gulp.src([
config.base + '/*',
'!' + config.base + '/*.html',
'!' + config.base + '/src',
'!' + config.base + '/test',
'!' + config.base + '/bower_components'
])
.pipe(gulp.dest(config.dist))
.pipe($.size({
title: 'copy'
}));
});
//clean temporary directories
gulp.task('clean', del.bind(null, [config.dist, config.tmp]));
//lint files
gulp.task('jshint', function() {
return gulp.src(config.js)
.pipe(reload({
stream: true,
once: true
}))
.pipe($.jshint())
.pipe($.jshint.reporter('jshint-stylish'))
.pipe($.if(!browserSync.active, $.jshint.reporter('fail')));
});
// babel
gulp.task('transpile', function() {
return gulp.src(config.js)
.pipe($.sourcemaps.init())
.pipe($.babel({
presets: ['es2015']
}))
.pipe($.sourcemaps.write('.'))
.pipe(gulp.dest(
path.join(config.tmp, 'src')
));
});
// inject js
gulp.task('inject:js', () => {
var injectJs = args.mock === 'no' ?
config.injectJs :
config.injectJs.concat(config.mockJS);
return gulp.src(config.index)
.pipe($.inject(
gulp
.src(injectJs, {
read: false
})
.pipe($.sort(sortModulesFirst)), {
starttag: '<!-- injector:js -->',
endtag: '<!-- endinjector -->',
transform: (filepath) => '<script src="' + filepath.replace('/client', 'tmp') + '"></script>'
}))
.pipe(gulp.dest(config.base));
});
/** ===================================
build tasks
======================================*/
//build files for development
gulp.task('build', ['clean'], function(cb) {
runSequence(['sass', 'templates', 'transpile', 'inject:js'], cb);
});
//build files for creating a dist release
gulp.task('build:dist', ['clean'], function(cb) {
//runSequence(['jshint', 'build', 'copy', 'copy:assets', 'images', 'test:unit'], 'html', cb);
runSequence(['jshint', 'build', 'copy', 'copy:assets', 'images'], 'html', 'clean:mock', cb);
});
// For aniden internal usage
// changed app root for labs server
gulp.task('labs:aniden', function() {
let base = `/hpe/mvno_portal/build/v${pkg.version}/`;
let html = gulp.src(config.dist + '/index.html', {
base: config.dist
})
.pipe($.replace('<base href="/">', `<base href="${base}">`))
.pipe(gulp.dest(config.dist));
let css = gulp.src(config.dist + '/**/*.css', {
base: config.dist
})
.pipe($.replace('url(/', `url(${base}`))
.pipe($.replace('url("/', `url("${base}`))
.pipe(gulp.dest(config.dist));
let js = gulp.src(config.dist + '/**/*.js', {
base: config.dist
})
.pipe($.replace('href="/"', `href="${base}"`))
.pipe(gulp.dest(config.dist));
return merge(html, css, js);
});
/** ===================================
tasks supposed to be public
======================================*/
//default task
gulp.task('default', ['serve']); //
//run unit tests and exit
gulp.task('test:unit', ['build'], function(cb) {
new KarmaServer(_.assign({}, karmaConfig, {
singleRun: true
}), cb).start();
});
// Run e2e tests using protractor, make sure serve task is running.
gulp.task('test:e2e', ['webdriver:update'], function() {
return gulp.src(protractorConfig.config.specs)
.pipe($.protractor.protractor({
configFile: 'build/protractor.config.js'
}))
.on('error', function(e) {
throw e;
});
});
//run the server, watch for file changes and redo tests.
gulp.task('serve:tdd', function(cb) {
runSequence(['serve', 'tdd'], cb);
});
//run the server after having built generated files, and watch for changes
gulp.task('serve', ['build'], function() {
browserSync(serverOptions());
gulp.watch(config.html, reload);
gulp.watch(config.scss, ['sass', reload]);
gulp.watch(config.js, ['jshint', 'transpile']);
gulp.watch(config.tpl, ['templates', reload]);
gulp.watch(config.assets, reload);
});
//run the app packed in the dist folder
gulp.task('serve:dist', ['build:dist'], function() {
browserSync(serverOptions());
});
You can use gulp-ng-config to add constant in you app module.
Or you a JSON as a config file inside your gulp:
//Gulp file
var fs = require('fs');
var settings = JSON.parse(fs.readFileSync('./config/config.json', 'utf8'));
....
gulp.task('statics', g.serve({
port: settings.frontend.ports.development,
...
}));
gulp.task('production', g.serve({
port: settings.frontend.ports.production,
root: ['./dist'],
...
}));

Reading Gmail from Protractor

I have a protractor test that uses mailinator for check if I am receiving some mails but I would like to use Gmail instead.
My test looks like this:
In my down-mail.js:
function findEmailBySubject(subject) {
console.log("searching");
var emails = element.all(by.repeater('email in emails')).all(by.binding('email.subject'));
var theOne;
emails.map(function (item) {
return item.getText();
}).then(function (names) {
for (var i = 0; i < names.length; i++) {
console.log(names[i]);
//console.log(theOne);
if (names[i].indexOf(subject) != -1) {
theOne = i;
console.log('Found alert email in position: ' + theOne);
}
}
// the email should be in the list:
expect(theOne).not.toBeUndefined();
});
}
function deleteAlertEmails() {
console.log('Deleting all emails');
var flow = protractor.promise.controlFlow()
var emails;
emails = element.all(by.repeater('email in emails')).all(by.binding('email.subject'));
emails.count().then(function(count) {
console.log(count);
for(var i=0; i<count; i++) {
browser.waitForAngular();
browser.driver.sleep(1000);
emails = element.all(by.repeater('email in emails')).all(by.binding('email.subject'));
emails.map(function (email) {
return email;
}).then(function (items) {
items[0].click();
// and some more waits after the click...
browser.waitForAngular();
browser.driver.sleep(2000);
element(by.partialButtonText('Delete')).click();
});
}
});
}
describe('Referee', function() {
it('should send an email notification on failure of a check', function() {
var flow = protractor.promise.controlFlow()
var s3 = new AWS.S3();
// start by deleting all old mails:
console.log("0. First we delete all emails from the inbox");
deleteAlertEmails();
// First delete the file that is in S3, so the check will fail
console.log("1. Now delete the file from S3");
flow.await(deleteFile(s3)).then(function() {
console.log('File deleted');
// Wait for 1.5 minute to give it time to see that the file is not there and send a mail
console.log("waiting for the DOWN mail...");
// using browser.wait(condition)
flow.await(browser.driver.sleep(60000)).then(function() {
console.log("waited");
// wait for angular:
browser.waitForAngular();
console.log("angular ready");
// Search for the alert email:
console.log("2. Search for the alert email");
findEmailBySubject("DOWN - An S3 test file");
// Now put the file back:
console.log("3. Now put the file back");
flow.await(uploadFile(s3)).then(function() {
console.log("Successfully uploaded data to " + BUCKET_NAME + "/" + FILE_NAME);
// // wait 15 seconds
// browser.driver.sleep(15000);
console.log("waiting for the UP mail...");
// wait to make sure the UP email is sent
flow.await(browser.driver.sleep(60000)).then(function() {
// Search for the alert email:
console.log("4. Search for the UP email");
findEmailBySubject("UP - An S3 test file");
// and now delete all the alert emails:
console.log("5. Now delete all the emails from the inbox");
deleteAlertEmails();
});
}, function(err) {
console.log("ERROR uploading file to S3");
throw new Error(err);
});
});
}, function(err) {
console.log('ERROR deleting file - stopping here');
console.log(err);
throw new Error(err);
});
});
});
This is my local-config.js file:
exports.config = {
seleniumAddress: '',
specs: ['down-mail.js'],
onPrepare: function() {
browser.driver.get('http://www.mailinater.com/inbox.jsp?to=juanazensie');
},
jasmineNodeOpts: {
onComplete: null,
isVerbose: true,
showColors: true,
includeStackTrace: true,
defaultTimeoutInterval: 360000
}
};
I would like to know please if is it possible to do this with the Gmail API and read these mails from Gmail using Protractor?
Thank you very much!!!

protractor and appium - cannot read property of undefined

I'm trying to lunch some selenium tests on an android device.
All the connection seams to work, as on the device i can see chrome opening and then the url change to data;
but after the url changes, everything stops saying
[launcher] Error: TypeError: Cannot read property 'Q' of undefined at module.exports (C:\src\angular-test\node_modules\wd-bridge\lib\wd-bridge.js:6:13)
I think it is related to wdBridge, as if i check wd-bridge,js, Q looks like this:
var Q = wd.Q;
I have no idea why its not working.
My protractor config file is the following:
"use strict";
exports.config = {
specs: ['e2e/*.js'],
framework: 'jasmine',
capabilities: {
'appium-version': '',
'platformName': 'Android',
'platformVersion': '6.0',
'deviceName': 'Android Device',
'autoWebView': true,
'app': "C:/src/angular-test/platforms/android/build/outputs/apk/android-debug.apk",
'udid': '',
'fullReset': true,
'browserName': 'chrome'
},
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 30000,
print: function () {
}
},
onPrepare: function () {
var DisplayProcessor = require('../node_modules/jasmine-spec-reporter/src/display-processor');
var SpecReporter = require('jasmine-spec-reporter');
function TimeProcessor(options) {
}
function getTime() {
var now = new Date();
return now.getHours() + ':' +
now.getMinutes() + ':' +
now.getSeconds()
}
TimeProcessor.prototype = new DisplayProcessor();
TimeProcessor.prototype.displaySuite = function (suite, log) {
return getTime() + ' - ' + log;
};
TimeProcessor.prototype.displaySuccessfulSpec = function (spec, log) {
return getTime() + ' - ' + log;
};
TimeProcessor.prototype.displayFailedSpec = function (spec, log) {
return getTime() + ' - ' + log;
};
TimeProcessor.prototype.displayPendingSpec = function (spec, log) {
return getTime() + ' - ' + log;
};
// add jasmine spec reporter
var reporter = new SpecReporter({
customProcessors: [TimeProcessor]
});
jasmine.getEnv().addReporter(reporter);
var wd = require('wd'),
wdBridge = require('wd-bridge')(wd);
wdBridge.initFromProtractor(exports.config);
},
//seleniumAddress: 'http://localhost:4723/wd/hub' //For mobile devices
seleniumAddress: 'http://localhost:4444/wd/hub' //For desktop
};
Any help, as always, is really appreciated.
Thanks
I managed to solve this myself.
Here's what i did:
Starting from the code above, as mentioned, Q was undefined.
This was because var Q = wd.Q that can be found inside wd-bridge.js file inside the node module folder is inside a function that needs 2 parameters.
I changed my protractor.config.js file like this:
"use strict";
var wd = require('wd');
var protractor = require ('protractor');
var wdBridge = require('wd-bridge')(protractor,wd);
exports.config = {
specs: ['e2e/*.js'],
framework: 'jasmine',
capabilities: {
'appium-version': '',
'platformName': 'Android',
'platformVersion': '6.0',
'deviceName': 'Android Device',
'autoWebView': true,
'app': "C:/src/angular-test/platforms/android/build/outputs/apk/android-debug.apk",
'udid': '',
'fullReset': true,
'browserName': 'chrome'
},
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 30000,
print: function () {
}
},
onPrepare: function () {
var DisplayProcessor = require('../node_modules/jasmine-spec-reporter/src/display-processor');
var SpecReporter = require('jasmine-spec-reporter');
function TimeProcessor(options) {
}
function getTime() {
var now = new Date();
return now.getHours() + ':' +
now.getMinutes() + ':' +
now.getSeconds()
}
TimeProcessor.prototype = new DisplayProcessor();
TimeProcessor.prototype.displaySuite = function (suite, log) {
return getTime() + ' - ' + log;
};
TimeProcessor.prototype.displaySuccessfulSpec = function (spec, log) {
return getTime() + ' - ' + log;
};
TimeProcessor.prototype.displayFailedSpec = function (spec, log) {
return getTime() + ' - ' + log;
};
TimeProcessor.prototype.displayPendingSpec = function (spec, log) {
return getTime() + ' - ' + log;
};
// add jasmine spec reporter
var reporter = new SpecReporter({
customProcessors: [TimeProcessor]
});
jasmine.getEnv().addReporter(reporter);
wdBridge.initFromProtractor(exports.config);
},
//seleniumAddress: 'http://localhost:4723/wd/hub' //For mobile devices
seleniumAddress: 'http://localhost:4444/wd/hub' //For desktop
};
it is now working perfectly.
Note: If you have wd, wdBridge or protractor modules not found, you need to install them NOT GLOBALLY (for example, npm install wd instead of npm install -g wd)
Hope this can help you out.

Can't get test through the end with protractor

I have simple test doing login and trying to check if it's success:
describe('My Angular App', function () {
describe('visiting the main homepage', function () {
beforeEach(function () {
browser.get('/');
element(By.id("siteLogin")).click();
});
it('should login successfully', function() {
element(By.name("login_username")).sendKeys("test#email.com");
element(By.name("login_password")).sendKeys("testpass");
element(By.id("formLoginButton")).click().then(function() {
browser.getCurrentUrl().then(function(url){
expect(url).toContain("profile");
});
});
});
});
});
It goes well until that last part where I'm checking URL, and in Selenium Server I get:
INFO - Executing: [execute async script: try { return (function (rootSelector, callback) {
var el = document.querySelector(rootSelector);
try {
if (window.getAngularTestability) {
window.getAngularTestability(el).whenStable(callback);
return;
}
if (!window.angular) {
throw new Error('angular could not be found on the window');
}
if (angular.getTestability) {
angular.getTestability(el).whenStable(callback);
} else {
if (!angular.element(el).injector()) {
throw new Error('root element (' + rootSelector + ') has no injector.' +
' this may mean it is not inside ng-app.');
}
angular.element(el).injector().get('$browser').
notifyWhenNoOutstandingRequests(callback);
}
} catch (err) {
callback(err.message);
}
}).apply(this, arguments); }
catch(e) { throw (e instanceof Error) ? e : new Error(e); }, [body]])
and also I get:
Failures:
1) My Angular App visiting the main homepage should login successfully
Message:
Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
My protractor-conf.js:
exports.config = {
seleniumAddress: 'http://localhost:4444/wd/hub',
baseUrl: 'http://localhost:8080/Mysite',
capabilities: {
'browserName': 'firefox' // muste use firefox because I can't get .click() to work in Chrome
},
specs: [
'spec-e2e/*.js'
],
framework: 'jasmine2',
jasmineNodeOpts: {
isVerbose: true,
showColors: true,
defaultTimeoutInterval: 30000
}
};
I appreciate any help on this one.
Thanks
Looks like there is a non-Angular page opened after a click. If this is the case, you need to turn the synchronization between Protractor and Angular off:
afterEach(function () {
browser.ignoreSynchronization = false;
});
it('should login successfully', function() {
element(By.name("login_username")).sendKeys("test#email.com");
element(By.name("login_password")).sendKeys("testpass");
browser.ignoreSynchronization = true;
element(By.id("formLoginButton")).click().then(function() {
expect(browser.getCurrentUrl()).toContain("profile");
});
});
Note that you don't need to explicitly resolve the promise returned by getCurrentUrl and can let the expect() do that for you implicitly.
You may also need to wait for the URL to change:
var urlChanged = function(desiredUrl) {
return browser.getCurrentUrl().then(function(url) {
return url == desiredUrl;
});
};
browser.wait(urlChanged("my desired url"), 5000);

Resources