Referencing Other Functions from Name Spaced JavaScript - javascript

So I am trying to consolidate a bunch of code into some nice NameSpaced functions, but am having a tough time getting it to all work together. For example, I have this (edited down for clarity):
YW.FB = function() {
return {
init: function(fncSuc, fncFail) {
FB.init(APIKey, "/services/fbconnect/xd_receiver.htm");
FB.Bootstrap.requireFeatures(["Connect"]);
if(typeof fncSuc=='function') fncSuc();
},
login: function(fncSuc) {
this.FB.Connect.requireSession(function() {
if(typeof fncSuc=='function') fncSuc();
});
},
getUserInfo: function() {
var userInfo = new Object;
FB.Facebook.apiClient.users_getInfo([FB.Facebook.apiClient.get_session().uid],["name"],function(result, ex){
userInfo.name = result[0]['name'];
userInfo.uid = result[0]['uid'];
userInfo.url = FBName.replace(/\s+/g, '-');
return userInfo;
})
}
};
}();
On a normal page I can just do:
FB.init(APIKey, "/services/fbconnect/xd_receiver.htm");
FB.Bootstrap.requireFeatures(["Connect"]);
var userInfo = new Object;
FB.Facebook.apiClient.users_getInfo([FB.Facebook.apiClient.get_session().uid],["name"],function(result, ex){
userInfo.name = result[0]['name'];
userInfo.uid = result[0]['uid'];
userInfo.url = FBName.replace(/\s+/g, '-');
return userInfo;
})
And it works.
I have been trying to do:
YW.init();
YW.login();
YW.getUserInfo();
But it doesn't work. I keep getting 'FB.Facebook is undefined' from YW.getUserInfo
I could be doing this all wrong too. So the FB.init, FB.Facebook stuff is using the facebook connect libraries. Am I doing this all wrong?

If you look at the JavaScript that your browser has parsed in Firebug or a similar web debugger do you see the Facebook Connect JavaScript there? Looks like it's not in scope, and since FB is at the global level that means it's not in scope at all. Has nothing to do with namespaces. Global in JavaScript is global everywhere.

Related

Prototypal Inheritence in Node JS

Being from the classical Inheritance Background(C#,Java etc.) , I am struggling with the Prototypal Way of doing it.
I am not understanding the basics also . Please explain and correct me on the following code block.
var util = require ('util');
function Student(choiceOfStream) {
this.choiceOfStream = choiceOfStream;
}
Student.prototype.showDetails = function() {
console.log("A student of "+this.choiceOfStream+" has a major in "+this.MajorSubject);
}
function ScienceStudent() {
Student.call(this,"Science");
}
function ArtsStudent() {
Student.call(this,"Arts");
}
util.inherits(ScienceStudent,Student);
util.inherits(ArtsStudent,Student);
var ArtsStudent = new ArtsStudent();
var ScienceStudent = new ScienceStudent();
ScienceStudent.prototype.MajorSubject = "Math";
ArtsStudent.prototype.MajorSubject = "Literature";
console.log(ArtsStudent.showDetails());
console.log(ScienceStudent.showDetails());
But the error I am getting is
What was I missing ?
There is no standard this.super_ property so I'm not sure where you got that from. If you're using util.inherits(), you can see a nice simple example of how to use it in the nodejs doc for util.inherits().
And, here's how your code could work:
var util = require ('util');
function Student(choiceOfStream) {
this.choiceOfStream = choiceOfStream;
}
Student.prototype.showDetails = function() {
console.log("A student of "+this.choiceOfStream+" has a major in "+this.MajorSubject);
}
function ScienceStudent() {
Student.call(this, "Science");
this.majorSubject = "Math";
}
function ArtsStudent() {
Student(this,"Arts");
this.majorSubject = "Literature";
}
util.inherits(ScienceStudent,Student);
util.inherits(ArtsStudent,Student);
FYI, in ES6 syntax, there is a super keyword which is part of a new way of declaring Javascript inheritance (still prototypal) you can read about here.

Multiple browsers and the Page Object pattern

We are using the Page Object pattern to organize our internal AngularJS application tests.
Here is an example page object we have:
var LoginPage = function () {
this.username = element(by.id("username"));
this.password = element(by.id("password"));
this.loginButton = element(by.id("submit"));
}
module.exports = LoginPage;
In a single-browser test, it is quite clear how to use it:
var LoginPage = require("./../po/login.po.js");
describe("Login functionality", function () {
var scope = {};
beforeEach(function () {
browser.get("/#login");
scope.page = new LoginPage();
});
it("should successfully log in a user", function () {
scope.page.username.clear();
scope.page.username.sendKeys(login);
scope.page.password.sendKeys(password);
scope.page.loginButton.click();
// assert we are logged in
});
});
But, when it comes to a test when multiple browsers are instantiated and there is the need to switch between them in a single test, it is becoming unclear how to use the same page object with multiple browsers:
describe("Login functionality", function () {
var scope = {};
beforeEach(function () {
browser.get("/#login");
scope.page = new LoginPage();
});
it("should warn there is an opened session", function () {
scope.page.username.clear();
scope.page.username.sendKeys(login);
scope.page.password.sendKeys(password);
scope.page.loginButton.click();
// assert we are logged in
// fire up a different browser and log in
var browser2 = browser.forkNewDriverInstance();
// the problem is here - scope.page.username.clear() would be applied to the main "browser"
});
});
Problem:
After we forked a new browser, how can we use the same Page Object fields and functions, but applied to a newly instantiated browser (browser2 in this case)?
In other words, all element() calls here would be applied to browser, but needed to be applied to browser2. How can we switch the context?
Thoughts:
one possible approach here would be to redefine the global element = browser2.element temporarily while being in the context of browser2. The problem with this approach is that we also have browser.wait() calls inside the page object functions. This means that browser = browser2 should be also set. In this case, we would need to remember the browser global object in a temp variable and restore it once we switch back to the main browser context..
another possible approach would be to pass the browser instance into the page object, something like:
var LoginPage = function (browserInstance) {
browser = browserInstance ? browserInstance : browser;
var element = browser.element;
// ...
}
but this would probably require to change every page object we have..
Hope the question is clear - let me know if it needs clarification.
Maybe you could write few functions to make the the browser registration/start/switch smoother. (Basically it is your first option with some support.)
For example:
var browserRegistry = [];
function openNewBrowser(){
if(typeof browserRegistry[0] == 'undefined'){
browseRegistry[0] = {
browser: browser,
element: element,
$: $,
$$: $$,
... whatever else you need.
}
}
var tmp = browser.forkNewDriverInstance();
var id = browserRegistry.length;
browseRegistry[id] = {
browser: tmp,
element: tmp.element,
$: tmp.$,
$$: tmp.$$,
... whatever else you need.
}
switchToBrowserContext(id);
return id;
}
function switchToBrowserContext(id){
browser=browseRegistry[id].browser;
element=browseRegistry[id].element;
$=browseRegistry[id].$;
$$=browseRegistry[id].$$;
}
And you use it this way in your example:
describe("Login functionality", function () {
var scope = {};
beforeEach(function () {
browser.get("/#login");
scope.page1 = new LoginPage();
openNewBrowser();
browser.get("/#login");
scope.page2 = new LoginPage();
});
it("should warn there is an opened session", function () {
scope.page1.username.clear();
scope.page1.username.sendKeys(login);
scope.page1.password.sendKeys(password);
scope.page1.loginButton.click();
scope.page2.username.clear();
scope.page2.username.sendKeys(login);
scope.page2.password.sendKeys(password);
scope.page2.loginButton.click();
});
});
So you can leave your page objects as they are.
To be honest I think your second approach is cleaner...
Using global variables can bite back later.
But if you don't want to change your POs, this can also work.
(I did not test it... sorry for the likely typos/errors.)
(You can place the support functions to your protractor conf's onprepare section for example.)
Look at my solution. I simplified example, but we are using this approach in current project. My app has pages for both user permissions types, and i need to do some complex actions same time in both browsers. I hope this might show you some new, better way!
"use strict";
//In config, you should declare global browser roles. I only have 2 roles - so i make 2 global instances
//Somewhere in onPrepare() function
global.admin = browser;
admin.admin = true;
global.guest = browser.forkNewDriverInstance();
guest.guest = true;
//Notice that default browser will be 'admin' example:
// let someElement = $('someElement'); // this will be tried to be found in admin browser.
class BasePage {
//Other shared logic also can be added here.
constructor (browser = admin) {
//Simplified example
this._browser = browser
}
}
class HomePage extends BasePage {
//You will not directly create this object. Instead you should use .getPageFor(browser)
constructor(browser) {
super(browser);
this.rightToolbar = ToolbarFragment.getFragmentFor(this._browser);
this.chat = ChatFragment.getFragmentFor(this._browser);
this.someOtherNiceButton = this._browser.$('button.menu');
}
//This function relies on params that we have patched for browser instances in onPrepare();
static getPageFor(browser) {
if (browser.guest) return new GuestHomePage(browser);
else if (browser.admin) return new AdminHomePage(browser);
}
openProfileMenu() {
let menu = ProfileMenuFragment.getFragmentFor(this._browser);
this.someOtherNiceButton.click();
return menu;
}
}
class GuestHomePage extends RoomPage {
constructor(browser) {
super(browser);
}
//Some feature that is only available for guest
login() {
// will be 'guest' browser in this case.
this._browser.$('input.login').sendKeys('sdkfj'); //blabla
this._browser.$('input.pass').sendKeys('2345'); //blabla
this._browser.$('button.login').click();
}
}
class AdminHomePage extends RoomPage {
constructor(browser) {
super(browser);
}
acceptGuest() {
let acceptGuestButton = this._browser.$('.request-admission .control-btn.admit-user');
this._browser.wait(EC.elementToBeClickable(acceptGuestButton), 10000,
'Admin should be able to see and click accept guest button. ' +
'Make sure that guest is currently trying to connect to the page');
acceptGuestButton.click();
//Calling browser directly since we need to do complex action. Just example.
guest.wait(EC.visibilityOf(guest.$('.central-content')), 10000, 'Guest should be dropped to the page');
}
}
//Then in your tests
let guestHomePage = HomePage.getPageFor(guest);
guestHomePage.login();
let adminHomePage = HomePage.getPageFor(admin);
adminHomePage.acceptGuest();
adminHomePage.openProfileMenu();
guestHomePage.openProfileMenu();

Get browser to show error when javascript fails

I'm new to JavaScript development. There's one problem I find annoying in particular, and I'm hoping there's a solution to it I haven't found yet.
The problem concerns feedback/debugability when JavaScript execution fails. Whenever 'normal' languages would throw an exeption, the JavaScript execution just stops without any message.
For example, I have this code:
var Something = function() {
var self = this;
self.oneMethod = function () { /*whatever*/ };
self.otherMethod = function() { /*whatever*/ };
}
var instance = new Something();
instance.oneMethod(); // fine
instance.wrongMethodCall(); // does not exist!
I would expect that last line to give an error, somehow, somewhere. But no, my browser console remains empty. Can I change something (either in the code or in my browser, Chrome) so that this will give an error, preferably with the line it occurred on (such as a throw statement would)?
Make sure that do not have filters set for your Developer Tools
Use console.log
Apply console.log('text here') in and around new functions during development to better track the code's progression. You should do something like the following:
var Something = function() {
console.log('Constructor for "Something" successfully called.');
var self = this;
self.oneMethod = function () { /*whatever*/ };
self.otherMethod = function() { /*whatever*/ };
}
console.log('Attempting to create new object: Something . . .');
var instance = new Something();
console.log('Object created: ', instance);
console.log('Performing "oneMethod" method of object "Something" . . .');
instance.oneMethod(); // fine
console.log('Performing "wrongMethodCall" method of object "Something" . . .');
instance.wrongMethodCall(); // does not exist!
This will help you to identify where your code is breaking, why, and can also return enumerated objects to help you review the methods, properties, and prototypes of new constructs.

mocking window.location.href in Javascript

I have some unit tests for a function that makes use of the window.location.href -- not ideal I would far rather have passed this in but its not possible in the implementation. I'm just wondering if its possible to mock this value without actually causing my test runner page to actually go to the URL.
window.location.href = "http://www.website.com?varName=foo";
expect(actions.paramToVar(test_Data)).toEqual("bar");
I'm using jasmine for my unit testing framework.
The best way to do this is to create a helper function somewhere and then mock that:
var mynamespace = mynamespace || {};
mynamespace.util = (function() {
function getWindowLocationHRef() {
return window.location.href;
}
return {
getWindowLocationHRef: getWindowLocationHRef
}
})();
Now instead of using window.location.href directly in your code simply use this instead. Then you can replace this method whenever you need to return a mocked value:
mynamespace.util.getWindowLocationHRef = function() {
return "http://mockhost/mockingpath"
};
If you want a specific part of the window location such as a query string parameter then create helper methods for that too and keep the parsing out of your main code. Some frameworks such as jasmine have test spies that can not only mock the function to return desired values, but can also verified it was called:
spyOn(mynamespace.util, 'getQueryStringParameterByName').andReturn("desc");
//...
expect(mynamespace.util.getQueryStringParameterByName).toHaveBeenCalledWith("sort");
I would propose two solutions which have already been hinted at in previous posts here:
Create a function around the access, use that in your production code, and stub this with Jasmine in your tests:
var actions = {
getCurrentURL: function () {
return window.location.href;
},
paramToVar: function (testData) {
...
var url = getCurrentURL();
...
}
};
// Test
var urlSpy = spyOn(actions, "getCurrentURL").andReturn("http://my/fake?param");
expect(actions.paramToVar(test_Data)).toEqual("bar");
Use a dependency injection and inject a fake in your test:
var _actions = function (window) {
return {
paramToVar: function (testData) {
...
var url = window.location.href;
...
}
};
};
var actions = _actions(window);
// Test
var fakeWindow = {
location: { href: "http://my/fake?param" }
};
var fakeActions = _actions(fakeWindow);
expect(fakeActions.paramToVar(test_Data)).toEqual("bar");
You need to simulate local context and create your own version of window and window.location objects
var localContext = {
"window":{
location:{
href: "http://www.website.com?varName=foo"
}
}
}
// simulated context
with(localContext){
console.log(window.location.href);
// http://www.website.com?varName=foo
}
//actual context
console.log(window.location.href);
// http://www.actual.page.url/...
If you use with then all variables (including window!) will firstly be looked from the context object and if not present then from the actual context.
Sometimes you may have a library that modifies window.location and you want to allow for it to function normally but also be tested. If this is the case, you can use a closure to pass your desired reference to your library such as this.
/* in mylib.js */
(function(view){
view.location.href = "foo";
}(self || window));
Then in your test, before including your library, you can redefine self globally, and the library will use the mock self as the view.
var self = {
location: { href: location.href }
};
In your library, you can also do something like the following, so you may redefine self at any point in the test:
/* in mylib.js */
var mylib = (function(href) {
function go ( href ) {
var view = self || window;
view.location.href = href;
}
return {go: go}
}());
In most if not all modern browsers, self is already a reference to window by default. In platforms that implement the Worker API, within a Worker self is a reference to the global scope. In node.js both self and window are not defined, so if you want you can also do this:
self || window || global
This may change if node.js really does implement the Worker API.
Below is the approach I have take to mock window.location.href and/or anything else which maybe on a global object.
First, rather than accessing it directly, encapsulate it in a module where the object is kept with a getter and setter. Below is my example. I am using require, but that is not necessary here.
define(["exports"], function(exports){
var win = window;
exports.getWindow = function(){
return win;
};
exports.setWindow = function(x){
win = x;
}
});
Now, where you have normally done in your code something like window.location.href, now you would do something like:
var window = global_window.getWindow();
var hrefString = window.location.href;
Finally the setup is complete and you can test your code by replacing the window object with a fake object you want to be in its place instead.
fakeWindow = {
location: {
href: "http://google.com?x=y"
}
}
w = require("helpers/global_window");
w.setWindow(fakeWindow);
This would change the win variable in the window module. It was originally set to the global window object, but it is not set to the fake window object you put in. So now after you replaced it, the code will get your fake window object and its fake href you had put it.
This works for me:
delete window.location;
window.location = Object.create(window);
window.location.href = 'my-url';
This is similar to cpimhoff's suggestion, but it uses dependency injection in Angular instead. I figured I would add this in case someone else comes here looking for an Angular solution.
In the module, probably the app.module add a window provider like this:
#NgModule({
...
providers: [
{
provide: Window,
useValue: window,
},
],
...
})
Then in your component that makes use of window, inject window in the constructor.
constructor(private window: Window)
Now instead of using window directly, use the component property when making use of window.
this.window.location.href = url
With that in place you can set the provider in Jasmine tests using TestBed.
beforeEach(async () => {
await TestBed.configureTestingModule({
providers: [
{
provide: Window,
useValue: {location: {href: ''}},
},
],
}).compileComponents();
});
IMO, this solution is a small improvement of cburgmer's in that it allows you to replace window.location.href with $window.location.href in the source. Granted I'm using Karma and not Jasmine, but I believe this approach would work with either. And I've added a dependency on sinon.
First a service / singleton:
function setHref(theHref) {
window.location.href = theHref;
}
function getHref(theHref) {
return window.location.href;
}
var $$window = {
location: {
setHref: setHref,
getHref: getHref,
get href() {
return this.getHref();
},
set href(v) {
this.setHref(v);
}
}
};
function windowInjectable() { return $$window; }
Now I can set location.href in code by injecting windowInjectable() as $window like this:
function($window) {
$window.location.href = "http://www.website.com?varName=foo";
}
and mocking it out in a unit test it looks like:
sinon.stub($window.location, 'setHref'); // this prevents the true window.location.href from being hit.
expect($window.location.setHref.args[0][0]).to.contain('varName=foo');
$window.location.setHref.restore();
The getter / setter syntax goes back to IE 9, and is otherwise widely supported according to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set
Here's my generic solution that requires an extra import in production code, but doesn't require dependency injection or writing individual wrapper functions like getHref().
Basically we toss the window into a separate file and then our prod code imports the window indirectly from that file.
In production, windowProxy === window.
In tests we can mutate the module which exports windowProxy and mock it with a new temporary value.
// windowProxy.js
/*
* This file exists solely as proxied reference to the window object
* so you can mock the window object during unit tests.
*/
export default window;
// prod/someCode.js
import windowProxy from 'path/to/windowProxy.js';
export function changeUrl() {
windowProxy.location.href = 'https://coolsite.com';
}
// tests/someCode.spec.js
import { changeUrl } from '../prod/someCode.js';
import * as windowProxy from '../prod/path/to/windowProxy.js';
describe('changeUrl', () => {
let mockWindow;
beforeEach(() => {
mockWindow = {};
windowProxy.default = myMockWindow;
});
afterEach(() => {
windowProxy.default = window;
});
it('changes the url', () => {
changeUrl();
expect(mockWindow.location.href).toEqual('https://coolsite.com');
});
});
You need to fake window.location.href while being on the same page.
In my case, this snipped worked perfectly:
$window.history.push(null, null, 'http://server/#/YOUR_ROUTE');
$location.$$absUrl = $window.location.href;
$location.replace();
// now, $location.path() will return YOUR_ROUTE even if there's no such route

How do I create methods for an HTML element?

I'm trying to create a simple, small and basic javascript framework just for learning purposes.
But the thing is that i'm allready stuck at the very basics.
I'm trying to do something like this:
$('testdiv').testFunction();
And the code i've written for that:
var elementID;
var smallFramework = {
$:function(id) {
this.elementID = id;
},
testFunction:function() {
alert(this.elementID);
}
};
window.$ = smallFramework.$;
But in return I get:
$('testdiv) is undefined
Can anyone help me with this small and hopefully easy question?
To get the behavior you're expecting, you need the $ function to return an object with a method named testFunction.
Try:
var smallFramework = // an object for namespacing
{
$:function(id) // the core function - returns an object wrapping the id
{
return { // return an object literal
elementID: id, // holding the id passed in
testFunction: function() // and a simple method
{
alert(this.elementID);
}
};
}
};
Of course, there are many other ways to achieve the behavior you desire.
If you're trying to add methods to an HTML element you could do something along these lines.
$ = function( elementId ) {
var element = document.getElementById( elementId );
element.testFunction = function(){
alert( this.id );
return this; // for chaining
}
return element;
}
$('test').testFunction();
Try
smallFramework.$('testdiv');
instead. According to the code you posted, that's where your $ function ended up.
Or alternatively, it looks like you're trying to replicate something like jQuery. You might want to try something like this.
var $ = smallFramework = (function () {
var f =
{
find:function(id) {
f.elementID = id;
return f; //every function should return f, for chaining to work
},
testFunction:function() {
alert(f.elementID);
return f;
}
}
return f.find //the find function will be assigned to $.
//and also assigned to smallFramework.
//the find function returns f, so you get access to testFunction via chaining
// like $("blah").testFunction()
})() //note this function gets called immediately.
this code may look confusing to someone new to JavaScript because it depends heavily on the concept of closures. I suggest that if this doesn't make sense, spend some time at Douglas Crockford's JavaScript website. This is important because the code above will bite if you happen to use this in the find function because this won't be bound to f, as you may expect it to be when you use it from $ or smallFramework.

Categories

Resources