I am trying to setup my phantomjs tests to work though karma, but I am unable to load the phantomjs 'webpage' and 'system' modules though requirejs.
here is part of the karma.config.js
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '.',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['requirejs'],
// list of files / patterns to load in the browser
files: [
'../ext/ext-all.js',
'test/jasmine/jasmine/jasmine.css',
'test/jasmine/jasmine/jasmine.js',
'test/jasmine/jasmine/jasmine-html.js',
'resources/webclientLogin-all.css',
'resources/webclient/webclient.css',
'app/controller/login/main.js',
'app/view/login/FormContainer.js',
'app/view/login/MustChangePasswordForm.js',
'app/view/MainView.js',
'app/Application.js',
'development.js',
'app.js',
'test/phantomjs/loginSuccess.js',
],
this is the phantomjs test code:
var page = require('webpage').create(), testindex = 0, loadInProgress = false;
var clientURL = "http://localhost:7001/client/";
page.onConsoleMessage = function(msg) {
console.log(msg);
};
page.onLoadStarted = function() {
loadInProgress = true;
console.log("load started");
};
page.onLoadFinished = function() {
loadInProgress = false;
console.log("load finished");
};
console.log('');
console.log("loginSuccess test BEGIN");
console.log('');
var steps = [
function() {
console.log("Load Page");
page.open(clientURL);
},
function() {
console.log("Populate Username and Password");
page.evaluate(function() {
var usernameField = Ext.ComponentQuery.query('textfield#login-username-textfield')[0];
var passwordField = usernameField.next('textfield#login-password-textfield');
usernameField.setValue('testuser');
passwordField.setValue('testpassword');
});
},
function() {
console.log("Fire Submit Button");
page.evaluate(function() {
var button = Ext.ComponentQuery.query('#login-button')[0];
button.fireEvent('click', button);
});
},
function() {
console.log("Verify redirect on successful login");
page.evaluate(function() {
console.log(location.href);
console.log('');
if (location.href.indexOf("/clientMB/") > -1) {
console.log("loginSuccess test SUCCESSFUL");
}
else {
console.log("loginSuccess test FAILURE");
}
console.log('');
});
}
];
this is the error i'm seeing
PhantomJS 1.9.7 (Windows 7) ERROR
Error: Module name "webpage" has not been loaded yet for context: _. Use requi
re([])
http://requirejs.org/docs/errors.html#notloaded
at C:/Users/shining.sun/AppData/Roaming/npm/node_modules/requirejs/require.js?
d84131f3e98422a49aa91d4f87cf96b245726d96:141
i'm using karma v0.12.16
"Require" is working only in the NodeJS environment, so it is unreachable from the Karma tests, because Karma launches a browser and directly injects your code into it, so no NodeJS stuff. Same issue is described here
Related
I'm bundling my javascript files using the task runner gulp js, during the development of an application I'm noticing a certain issue.
When I add the new feature(reveal a password) script refuses to work because of the form modal script which can be seen below.
'use strict';
var modal__button = document.getElementById("enquiry-form-trigger");
var close__button = document.getElementById("close");
modal__button.addEventListener("click", function (){
var modal = document.getElementById("modal-form");
modal.classList.add("fadeIn");
modal.style.visibility = "visible";
});
close__button.addEventListener("click", function (){
var modal = document.getElementById("modal-form");
modal.classList.remove("fadeIn");
modal.style.visibility = "hidden";
});
When the above script and this other script below
"use strict"
document.getElementById("password-reveal-modal").addEventListener("click", function (){
var x = document.getElementById("password-modal");
if (x.type === "password") {
x.type = "text";
} else {
x.type = "password";
}
});
The password reveal feature doesn't work, but when I paste it in chrome's dev tools works perfectly.
I'm not sure why it wont work without pasting it into the dev tools, it's baffling me, I'm not sure if its my setup or if its the custom javascript.
This is my gulp file setup in case anyone wants to check it, I don't see an issue but Ive only been using gulp for about 3 or 4 months.
var gulp = require("gulp"),
sass = require("gulp-sass"),
image = require("gulp-image"),
concat = require("gulp-concat"),
browserSync = require('browser-sync').create(),
reload = browserSync.reload,
minifyEjs = require("gulp-minify-ejs"),
stripEJSComments = require('gulp-strip-comments'),
nodemon = require('gulp-nodemon'),
plumber = require("gulp-plumber"),
ejs = require("ejs"),
uglify = require("gulp-uglify");
//Build task
gulp.task("build", ["ejs", "styles", "images", "javascript", "routes", "models", "middleware"], function () {
console.log("Build Success");
});
//start up sequence tasks
gulp.task('init', ["nodemon"], function () {
browserSync.init({
proxy: 'http://localhost:2000', //Index.js port number
port: 2128, // The port browser sync runs on
serveStatic: [ './public/', "./assets/"], // What files browser sync should have access to
reloadOnRestart: true, // Enable auto reload
ghostMode:false, //Stops session mirroring
open: "external", //Opens up on an external address (xxx.xxx.x.xx:3128)
});
});
//Starts the express server
gulp.task('nodemon', function (done) {
var running = false; //Default State
return nodemon({
script: 'index.js', //Index file for the JS project
watch: ["./assets/", "./public/"] //What nodemon has access to
})
.on('start', function () {
if (!running) {
done();
}
running = true;
})
//Minor Delay Of 500ms Upon Restart
.on('restart', function () {
setTimeout(function () {
reload();
}, 500);
});
});
//SCSS Task
gulp.task("styles", function () {
gulp.src("./assets/stylesheet/APP.scss")
.pipe(plumber())
.pipe(sass({
outputStyle: 'compressed'
}))
.pipe(gulp.dest("./public/stylesheet/"))
.pipe(browserSync.stream({ stream: true }));
});
//Compiles the express route/s
gulp.task("routes", function () {
gulp.src([
"./assets/routes/*.js"
])
.pipe(plumber())
.pipe(gulp.dest("./public/routes/"))
.pipe(browserSync.stream({ stream: true }));
});
//Compiles the express route/s
gulp.task("models", function () {
gulp.src("./assets/models/*.js")
.pipe(plumber())
.pipe(gulp.dest("./public/models/"))
.pipe(browserSync.stream({ stream: true }));
});
//Image minification
gulp.task("images", function () {
return gulp.src("./assets/images/*")
.pipe(image())
.pipe(gulp.dest("./public/images"))
.pipe(browserSync.stream({ stream: true }));
});
//Client javascript
gulp.task("javascript", function () {
gulp.src([
"./node_modules/jquery/dist/jquery.js",
"./node_modules/tether/dist/js/tether.js",
"./node_modules/bootstrap/dist/js/bootstrap.js",
"./assets/scripts/**/**/*.js"
])
.pipe(plumber())
.pipe(concat("main.js"))
.pipe(gulp.dest("./public/scripts/"))
.pipe(browserSync.stream({ stream: true }));
});
//Middleware task
gulp.task("middleware", function () {
gulp.src("./assets/middleware/*.js")
.pipe(plumber())
.pipe(concat("index.js"))
.pipe(gulp.dest("./public/middleware/"))
.pipe(browserSync.stream({ stream: true }));
});
//EJS task
gulp.task("ejs", function () {
gulp.src("./assets/views/**/*.ejs")
.pipe(plumber())
.pipe(stripEJSComments())
.pipe(minifyEjs({}))
.pipe(gulp.dest("./public/views"))
.pipe(browserSync.stream({ stream: true }));
});
//Default task array
gulp.task("default", ["init", "build"], function (done) {
gulp.watch("./assets/stylesheet/**/*.scss", ["styles"]);
gulp.watch("./assets/scripts/*", ["javascript"]);
gulp.watch("./assets/routes/*.js", ["routes"]);
gulp.watch("./assets/models/*.js",["models"]);
gulp.watch("./assets/images/*",["images"]);
gulp.watch("./assets/views/**/*.ejs",["ejs"]);
browserSync.reload();
done();
});
The two files which are causing the issue are the only files as I have tested each files and its only these two files weirdly so something is causing it to clash.
If you want me to upload my project to github just let me know and I will upload the latest version to my update branch.
I have exhausted all my knowledge into this problem and I am completely stuck now.
If anyone could help a fellow developer out it would be greatly appreciated.
cheers,
alex
I needed to ensure the DOM had fully loaded before the script could be executed.
Can Some give an elaborate example of using Custom Jasmine Reporter . I would like someone to help me with a sample test with two assertions . how to add the reporter in protractor conf.js and how it can help me . No where in the internet there is a example apart from just the reference .
check the one I use:
First check if all the necessary dependencies are installed (check the begin of the code)
Then copy+paste this to you Conf.js:
//In my case I installed the dependencies locally thats why comes from lib folder
var jasmineReporters = require('./lib/node_modules/jasmine-reporters');
var HTMLReport = require('./lib/node_modules/protractor-html-reporter-2');
var fs = require('./lib/node_modules/fs-extra');
onPrepare: function () {
fs.emptyDir('./Execution_Results/reports/xml/', function (err) {
if (err != ""){
console.log(err);
}
});
fs.emptyDir('./Execution_Results/reports/results/screenshots', function (err) {
if (err != ""){
console.log(err);
}
});
jasmine.getEnv().addReporter(new jasmineReporters.JUnitXmlReporter({
consolidateAll: true,
savePath: './Execution_Results/reports/xml/',
filePrefix: 'xmlresults'
}));
jasmine.getEnv().addReporter({
specDone: function (result) {
//if (result.status == 'failed') {
browser.getCapabilities().then(function (caps)
{
var browserName = caps.get('browserName');
browser.takeScreenshot().then(function (png) {
var stream = fs.createWriteStream('./Execution_Results/reports/results/screenshots/' + browserName + '-' + result.fullName + '.png');
stream.write(new Buffer(png, 'base64'));
stream.end();
});
});
//}
}
});
},
//HTMLReport called once tests are finished
onComplete: function() {
var browserName, browserVersion;
var capsPromise = browser.getCapabilities();
capsPromise.then(function (caps) {
browserName = caps.get('browserName');
browserVersion = caps.get('version');
platform = caps.get('platform');
testConfig = {
reportTitle: 'Protractor Test Execution Report',
outputPath: './',
outputFilename: 'Execution_Results/reports/results/IV2_Test_Results',
screenshotPath: './screenshots/',
testBrowser: browserName,
browserVersion: browserVersion,
modifiedSuiteName: false,
screenshotsOnlyOnFailure: true,
testPlatform: platform
};
new HTMLReport().from('./Execution_Results/reports/xml/xmlresults.xml', testConfig);
});
},
jasmineNodeOpts: {
showColors: true, // Use colors in the command line report.
// If true, display spec names.
isVerbose: true,
},
the folders will be created automatically inside the folder where your conf.js is located so after the execution just access the 'Execution_Results/reports' and open the html report
OnPrepare will generate the xml file with all the results
OnComplete will transform the xml into html report
I'm using this reporter, Just follow the steps from this link to set the conf.js https://www.npmjs.com/package/protractor-jasmine2-screenshot-reporter
(I'm not using jQuery) Hi! I'm starting with protractor and cucumber and i'm testing a login page.
I'm trying to insert values on a form for the login, but when i lunch the configuration file to lunch the test, Chrome open the login page but don't displays the values that i setted for the required fields.
Clicking on sumbit button, the page should be redirect to another. Can anyone help me? How i have to change my step definition file to make it works? Thank you
I think that there are some problems like in configuration and others.
Here is step definition:
This is my new step definition file:
Given("I'm on site login page", function () {
//return pending;
browser.driver.get('https://www.websiteurl.com/login.html');
browser.sleep(20000);
});
When('I see the submit-button', function () {
// Write code here that turns the phrase above into concrete actions
//var sumbit = browser.executeScript('document.getElementById("submit-//wrap.cf.input-formFields")');
var sumbit = element(by.css('.submit-wrap.cf.input-formFields'));
expect(sumbit).to.not.be.null;
});
When('I filled all the mandatory fields', function () {
// Write code here that turns the phrase above into concrete actions
window.onload = function(){
var bookingNumberField = browser.executeScript('document.getElementById("variation2-bookingNumber").getText()');
var firstNameField = browser.executeScript('document.getElementById("variation2-firstName").getText()');
var lastNameField = browser.executeScript('document.getElementById("variation2-lastNameField").getText()');
var dobMonth = browser.executeScript('document.getElementById("month").getText()');
var dobDay = browser.executeScript('document.getElementById("day").getText()');
var dobYear = browser.executeScript('document.getElementById("year").getText()');
// var firstNameField = document.getElementById("variation2-firstName");
// var lastNameField = document.getElementById("variation2-lastName");
// var dobMonth = document.getElementById("month");
// var dobDay = document.getElementById("day");
// var dobYear = document.getElementById("year");
browser.sleep(1000);
//browser.waitForAngular();
//browser.executeScript to cut eventually
browser.executeScript.bookingNumberField.clear().sendKeys('WJXMHH');
browser.executeScript.firstNameField.clear().sendKeys('Mark');
browser.executeScript.lastNameField.clear().sendKeys('Altria');
element(by.cssContainingText('option', 'March')).click();
element(by.cssContainingText('option', '10')).click();
element(by.cssContainingText('option', '1991')).click();
TermsChkbxLabel = element(by.css("label[for='checkboxb']"));
TermsChkbxLabel.click();
}
}); //loginBtn.click();
Then('I am able to click on it to login', function () {
// var ptor = protractor.getInstance();
// ptor.ignoreSynchronization = true;
// var login_b = browser.executeScript('document.getElementById("login-button").click()');
//var login_b = document.getElementsByClassName("login-button").click();
// ptor.sleep(10000);
// var expectedUrl = ptor.getCurrentUrl();
// //expect(expectedUrl).toEqual('https://www.websiteurl.com/newpage.html');
});
Then('I am able to open the new page', function () {
var login_b = element(by.css('.login-button'));
login_b.click();
// var ptor = protractor.getInstance();
// ptor.ignoreSynchronization = true;
// var login_b = document.getElementsByClassName("login-button").click();
// ptor.sleep(10000);
// var expectedUrl = ptor.getCurrentUrl();
//
});
Here is the protractor conf.js:
var seleniumServer = require('selenium-server')
var nightwatchCucumber = require('nightwatch-cucumber')
require('babel-core/register');
var nightwatchCucumberConf = {
runner: 'nightwatch',
featureFiles: 'features',
stepDefinitions: 'features/step_definitions/testing_1_6.js',
closeSession: 'afterFeature'
};
exports.config = {
seleniumAddress: 'http://127.0.0.1:4444/wd/hub',
getPageTimeout: 60000,
allScriptsTimeout: 500000,
framework: 'custom',
// path relative to the current config file
frameworkPath: require.resolve('protractor-cucumber-framework'),
plugins: [{
path: require.resolve('protractor-console'),
logLevels: ['severe']
}],
directConnect: true, //chrome only
jasmineNodeOpts: {},
onPrepare: function() {},
capabilities: {
'browserName': 'chrome'
},
// Spec patterns are relative to this directory.
specs: [
'features/*.feature'
],
baseURL: 'https://www.websiteurl.com/login.html',
cucumberOpts: {
//require: 'features/step_definitions/**/*.js',
require: 'features/step_definitions/testing_1_6.js',
tags: false,
// format: 'pretty',
profile: false,
'no-source': true
}
};
I have this error too:
[12:57:27] E/launcher - Error while waiting for Protractor to sync with the page: "both angularJS testability and angular testability are undefined. This could be either because this is a non-angular page or because your test involves client-side navigation, which can interfere with Protractor's bootstrapping. See http://git.io/v4gXM for details"
[12:57:27] E/launcher - Error: Error while waiting for Protractor to sync with the page: "both angularJS testability and angular testability are undefined. This could be either because this is a non-angular page or because your test involves client-side navigation, which can interfere with Protractor's bootstrapping.
Step definition file testing_1_6.js:
// chai is an assertion library
var chai = require('chai');
// chai-as-promised is an helper to handle promise
var chaiAsPromised = require('chai-as-promised')
chai.use(chaiAsPromised);
expect = chai.expect;
Given("I'm on site login page", function() {
browser.driver.get('https://www.websiteurl.com/login.html');
return browser.sleep(20000);
});
When('I see the submit-button', function() {
var sumbitBtn = element(by.css('.submit-wrap.cf.input-formFields'));
return expect(sumbitBtn.isDisplayed()).to.eventually.be.true;
});
When('I filled all the mandatory fields', function() {
element(by.id('variation2-bookingNumber')).sendKeys('WJXMHH');
element(by.id('variation2-firstName')).sendKeys('Mark');
element(by.id('variation2-lastNameField')).sendKeys('Altria')
element(by.cssContainingText('#month > option', 'March')).click();
element(by.cssContainingText('#day > option', '10')).click();
element(by.cssContainingText('#year > option', '1991')).click();
return element(by.css("label[for='checkboxb']")).click();
});
Then('I am able to click on it to login', function() {
return element(by.id('login-button')).click();
});
Then('I am able to open the new page', function() {
var newPageUrl = 'https://www.websiteurl.com/newpage.html';
browser.sleep(10000);
return expect(browser.getCurrentUrl()).to.eventually.equal(newPageUrl);
});
protractor conf.js:
exports.config = {
seleniumAddress: 'http://127.0.0.1:4444/wd/hub',
getPageTimeout: 60000,
allScriptsTimeout: 500000,
framework: 'custom',
frameworkPath: require.resolve('protractor-cucumber-framework'),
plugins: [{
path: require.resolve('protractor-console'),
logLevels: ['severe']
}],
directConnect: true, //chrome only
onPrepare: function() {
browser.ignoreSynchronization = true;
},
capabilities: {
browserName: 'chrome'
},
specs: [
'features/*.feature'
],
cucumberOpts: {
require: [
'features/step_definitions/testing_1_6.js'
]
}
};
browser.waitForAngularEnabled(false);
I'm building my angularjs protractor e2e test to the page objects pattern. I'm facing trouble with converting my script in to page object.
Here is my conf.js
// conf.js
exports.config = {
framework: 'jasmine',
seleniumAddress: 'http://localhost:4444/wd/hub',
specs: ['employee.js']
}
Here is my employee.js
// spec.js
var EmpPageObject = require('./EmpPageObject.js');
describe('Protractor Demo App', function() {
it('should have a title', function() {
var empPageObject = new EmpPageObject();
empPageObject.get();
empPageObject.setName('mee');
empPageObject.setPassword('123');
});
});
Here is my EmpPageObject.js
var EmpPageObject = function() {
var nameInput = element(by.model('login.user_name'));
var passwordInput = element(by.model('login.password'));
var addButton = element(by.css('.btn'));
this.get = function() {
browser.get('http://');
};
this.setName = function(name) {
nameInput.sendKeys(name);
};
this.setPassword = function(password) {
passwordInput.sendKeys(password);
};
addButton.click();
};
But, my script fails giving the following error.
Failures:
1) Protractor Demo App should have a title
Message:
Failed: EmpPageObject is not defined
This may be a dumb question. But, I cannot find the error since this is my first test. :)
Look like you copy-paste code from here
https://github.com/angular/protractor/blob/f9c8a37f7dbec1dccec2dde0bd6884ad7ae3f5c7/docs/tutorial.md
describe('Protractor Demo App', function() {
it('should have a title', function() {
browser.get('http://juliemr.github.io/protractor-demo/');
expect(browser.getTitle()).toEqual('Super Calculator');
});
});
Here is protractor try to get resource and check - is it have title.
This function return true or false to make test. In your case, function return undefined, it is equal to false, test fail and you get error message.
The problem is in stream reloading page
Just reload method work correctly
But when I user browserSync.stream() (browserSync.reload({stream: true})) it's not working
It's my browser sync init function
function browserSyncInit(baseDir, browser) {
browser = browser === undefined ? 'default' : browser;
var routes = null;
if(baseDir === conf.paths.src || (util.isArray(baseDir) && baseDir.indexOf(conf.paths.src) !== -1)) {
routes = {
'/bower_components': 'bower_components'
};
}
var server = {
baseDir: baseDir,
routes: routes,
middleware: proxyMiddleware('http://0.0.0.0:8080')
};
var nodemonConfig = {
cwd: path.normalize(__dirname + '/../../'),
script: 'server/server.js',
ext: 'js json',
ignore: ['client/**/*.*'],
env: {'PORT': '8080'}
};
var serverStarted;
nodemon(nodemonConfig)
.on('start', function () {
if (serverStarted) return;
browserSync.init(null, {
startPath: '/',
open: false,
server: server,
browser: browser
});
serverStarted = true;
});
}
Proxy server it's Loopback application (may be problem in this)
It's task for reloading styles and scrips
gulp.task('styles-reload', ['styles'], function() {
return buildStyles()
.pipe(browserSync.stream());
});
gulp.task('scripts-reload', ['scripts'], function() {
return buildScripts()
.pipe(browserSync.stream());
});
Streams are for injecting scripts/css/etc., from a task's Gulp stream, which is why in the documentation, it mentions to place it after the gulp.dest.
If you're looking to manually reload the BrowserSync page, you can do that with .reload in your two functions, otherwise, you'll need to pass through the files into your reload tasks, since it looks like you're calling those tasks from elsewhere.
To add to this, I don't see a reason to separate the two tasks (styles/scripts with their respective -reload tasks). You should just pipe it after the dest, so that you don't have to mess with starting a new stream or merging between tasks.