How to allow JQuery event handler to access variables in module pattern - javascript

var MODULE = (function() {
var app = {
hi: "hi mom", // I can't access this. Oh' what do I do?
onSubmitClick: function() {
$('button').click(function() {
console.log(hi); // I want to access the above hi variable..eeek!
})
},
run: function() {
this.onSubmitClick()
}
}
return app
}());
var newApp = MODULE;
newApp.run();

hi is not a variable, it is a property of the object app
var MODULE = (function () {
var app = {
hi: "hi mom",
onSubmitClick: function () {
$('button').click(function () {
console.log(app.hi); //use the app object and access the property
})
},
run: function () {
this.onSubmitClick()
}
}
return app
}());
var newApp = MODULE;
newApp.run();
Demo: Fiddle

You can do something like this also.
var app = {
hi: "hi mom",
onSubmitClick: function (cthis) {
$('button').click(function () {
alert(cthis.hi); //use the app object and access the property
})
},
run: function () {
this.onSubmitClick(this);
//-------------------^ this is referring app
}
}
Demo

Related

How to mock chrome.cookies.getAll using Jasmine?

I have the following code in background.js
var allCookies = [];
function getAllCookies() {
chrome.cookies.getAll({}, function(cookies) {
for (var i in cookies) {
allCookies.push(cookies[i])
}
}
});
}
Now in specs.js, I have written the following code to test the getAllCookies method -
describe('getAllCookies', function() {
beforeEach(function() {
chrome = {
cookies: {
getAll : function() {
return [
'cookie1',
'cookie2'
]
}
}
};
spyOn(chrome.cookies,'getAll');
});
it('should updated global variable allCookies', function() {
getAllCookies();
expect(allCookies).toEqual(['cookie1','cookie2'])
})
})
But the test is failing as allCookies = [] but it should be equal to ['cookie1','cookie2']
Can someone please help me to mock such chrome APIs (say chrome.cookies.getAll) which takes callback function as argument?

How to inheritance functions from a base js file in Protractor?

I moved from automation framework development with java to protractor & javascript so this is new to me. In my protractor framework I need to create a base screen js file with global functions that can be called from other screens js files. See the following example. How to make login.js inheritance all functions from base.js so the test in loginTest.js will work when calling base.js functions directly from login.js?
base.js
var base= function(){
var that = {
navigateToLogin: function(url){
browser.get(url);
browser.driver.manage().window().maximize();
return require('login.js');
},
click: function(element, page){
element.click();
console.log('LOG: Clicked on element ' + element);
return that || page;
},
insert: function(element, text){
element.clear().then(function() {
element.sendKeys(text);
console.log('LOG: Insert text: ' +text);
});
return that;
},
};
return that;
};
module.exports = new base();
login.js
var login = function(){
var that = {
func1: function() {
// do something
return that
},
func2: function() {
// do something
return that;
},
};
return that;
};
module.exports = new login();
loginTests.js
describe('Login tests - ', function() {
var loginPage = require('login.js');
describe('Success login: ', function () {
beforeEach(function () {
loginPage.navigateToLogin(“http://login.url”);
});
it("Success login as admin",function(){
loginPage.insert(“element(by.name("username"))”,”admin#mail”l)
.insert(“element(by.name("password"))”,”12345”)
.click(“element(by.name("loginButton"))”,“home.js”);
});
});
});
If you are using node.js > 4 (5 and more) try to use ES6 classes -
basepage.js:
class BasePage {
constructor() {
}
open() {
browser.get(url);
browser.driver.manage().window().maximize();
}
}
exports = BasePage
loginpage.js:
class LoginPage extends BasePage {
constructor() {
super()
}
login(username, password) {
//do your login stuff here
}
}
exports = LoginPage
Then in your test:
let LoginPage = require('loginpage.js');
describe('Login tests - ', function () {
let loginPage = new LoginPage()
beforeEach(function () {
loginPage.open('/login')
})
it("Success login as admin", function () {
loginPage.login('admin', '123456')
})
})

Error while import in typescript

I have created a sample typescript jquery project and I am facing issue while import
error is:
require.js:143 Uncaught Error: Module name "ajaxLib" has not been
loaded yet for context: _. Use require([])
home.ts:
/// <reference path="jquery.d.ts" />
import { AjaxContainer } from "./ajaxLib";
module Home {
export class HomeContainer {
private content: HTMLElement;
constructor(value?: any) {
// document.body.innerHTML = value;
var animal = new AjaxContainer();
var el: HTMLElement = document.getElementById('grid1');
$(el).css({"color": "blue" });
}
}
}
window.onload = () => {
var object1 = new Home.HomeContainer("ram");
}
Complete project is on github : https://github.com/focode/typescriptJquery/tree/master
Also I am successfully able to use jquery.
After changing module to amd the converted js file now includes define
define(["require", "exports", "./ajaxLib"], function (require, exports, ajaxLib_1) {
"use strict";
var Home;
(function (Home) {
var HomeContainer = (function () {
function HomeContainer(value) {
var animal = new ajaxLib_1.AjaxContainer();
var el = document.getElementById('grid1');
$(el).css({ "color": "blue" });
}
return HomeContainer;
}());
Home.HomeContainer = HomeContainer;
})(Home || (Home = {}));
window.onload = function () {
var object1 = new Home.HomeContainer("ram");
};
});
but on browser console I am getting:
require.js:143 Uncaught Error: Mismatched anonymous define() module: function (require, exports, ajaxLib_1) {
"use strict";
var Home;
(function (Home) {
var HomeContainer = (function () {
function HomeContainer(value) {
var animal = new ajaxLib_1.AjaxContainer();
var el = document.getElementById('grid1');
$(el).css({ "color": "blue" });
}
return HomeContainer;
}());
Home.HomeContainer = HomeContainer;
})(Home || (Home = {}));
window.onload = function () {
var object1 = new Home.HomeContainer("ram");
};
}
http://requirejs.org/docs/errors.html#mismatch

Protractor Page objects - TypeError: Object #<Object> has no method 'methodName'

I'm trying to write a simple test using page objects pattern - based on the 'docs/page-objects'.
I created a file describing the page object and other using this page object to test a page.
//page object
var LoginPage = function() {
this.userInput = browser.driver.findElement(by.id('username'));
this.pwdInput = browser.driver.findElement(by.id('password'));
this.btnEnter = browser.driver.findElement(by.id('btnLogin'));
this.get = function(){
browser.get('http://example.com');
};
this.setUser = function (user){
this.userInput.sendKeys(user);
};
this.setPasswd = function (password) {
this.pwdInput.sendKeys(password);
};
this.clickBtnEnter = function (){
btnEnter.click();
};};
The spec file:
var loginPage = require('./LoginPage.js');
describe('myApp', function() {
it('should save contract config', function (){
loginPage.get();
loginPage.setUser('userid');
loginPage.setPasswd('passwd');
loginPage.clickBtnEnter();
});
});
The following error is shown when I run this test: TypeError: Object # has no method 'get' - at this line: loginPage.get();.
When I was searching for this problem I found various approaches about using page objects in Protractor, such as Astrolable.
Now I am not sure about the correct usage of page objects.
Do you have any ideas about how I can fix this test?
Thank you guys.
Try this:
Ensure you have the following in your LoginPage.js file
module.exports = LoginPage;
Add the missing new keyword
var LoginPage = require('./LoginPage.js');
var loginPage = new LoginPage();
After trying the above syntax (no success) I rewrote the page object using the Astrolable. Now it works! My test looks like this:
//pageobject
'use strict';
var env = require('./environment.js')
var LoginPage = function () {
browser.driver.get('http://example.com');
};
LoginPage.prototype = Object.create({}, {
userInput: { get: function() { return browser.driver.findElement(by.id('username'));}},
pwdInput: { get: function() { return browser.driver.findElement(by.id('password'));}},
btnEnter: { get: function() { return browser.driver.findElement(by.id('btnLogin'));}},
setUser: { value: function (loginName) {
this.userInput.sendKeys(loginName);
}},
setPasswd: { value: function (loginPass) {
this.pwdInput.sendKeys(loginPass);
}},
clickBtnEnter: { get: function() { return this.btnEnter.click();}}
});
module.exports = LoginPage;
Spec file:
'use strict';
var loginPage = require('./LoginPage.js');
describe('myApp', function() {
var poLogin = new loginPage();
it('should save contract config', function (){
poLogin.setUser('userid');
poLogin.setPasswd('passwd');
poLogin.clickBtnEnter;
});
});
Now it is working fine.
Thanks for answering.

javascript calling parent method from child

I have the following object:
var party =
{
food:
{
serve: function () {
// I want to call turnOff method from here
}
cleanUp: function () {
}
}
music:
{
turnOff: function () {
}
}
}
So as the comment points out, I want to call the turnOff method from the music object, how can I do this? this refers to the food object but I need to access the music object...
var party =
{
food:
{
serve: function () {
party.music.turnOff();
},
cleanUp: function () {
}
},
music:
{
turnOff: function () {
}
}
}
Use a constructor instead of a literal with a variable referencing the parent object
var party = new (function()
{
var self = this;
this.food =
{
serve: function () {
self.music.turnoff();
},
cleanUp: function () {
}
}
this.music =
{
turnOff: function () {
}
}
})();
Call it as party.music.turnOff().
FYI, your above code block isn't valid. You're missing some commas - after the serve and food closing braces.

Categories