Protractor: Unable to reach variables within closure set in the parent function

I have a code snippet in one of my JS files that looks like this:

// test/lib/UserHelper.js

'use strict';
var Firebase = require('firebase');

exports.createUser = function (email, password) {
  browser.executeAsyncScript(function (done) {
    var $firebaseSimpleLogin = angular.inject(['ng', 'firebase']).get('$firebaseSimpleLoging');
    var firebaseRef = new Firebase('https://urltoapplication.firebaseio.com');
    var auth = $firebaseSimpleLogin(firebaseRef);

    auth.$createUser(email, password);

    done();
  });
};

When I try to call it within my test as shown below:

// test/settings/company.spec.js

'use strict';
var user = require('../lib/UserHelper');

describe('company specs', function () {

  beforeEach(function () {
    user.createUser('<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dbafbea8af9bafbea8aff5b8b4b6">[email protected]</a>', 'test');
  });
});

The call to

user.createUser('<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2b5f4e585f6b5f4e585f05484446">[email protected]</a>', 'test');
in the beforeEach callback fails with
UnknownError: email is not defined
at
auth.$createUser(email, password);
.

I am curious why the email variable is not accessible in the callback function. Is there a way to pass arguments to the closing function that were initially passed to the createUser function?


After consulting with Andres D., I found a solution that worked for me. Here is the updated code:

exports.createUser = function (data) {
  browser.executeAsyncScript(function (data, done) {
    var $firebaseSimpleLogin = angular.inject(['ng', 'firebase']).get('$firebaseSimpleLoging');
    var firebaseRef = new Firebase('https://urltoapplication.firebaseio.com');
    var auth = $firebaseSimpleLogin(firebaseRef);

    auth.$createUser(data.email, data.password);

    done();
  }, data);
};

Answer №1

During a recent Angular meetup, I shared this practical example:

If you need to pass more than one value when using executeAsyncScript, it is advisable to encapsulate them in an object:

module.exports = {
  create: function(data) {
    return browser.executeAsyncScript(function(data, callback) {
      var api = angular.injector(['ProtractorMeetupApp']).get('apiService');
      api.member.save(data, function(newItem) {
        callback(newItem._id);
      })
    }, data);
  }
};

create({email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2f5c4b496f5c4b49el9kwokml">[email protected]</a>', password: 'sfd'}).then(function(response){
  // Handle response here.
})

Link to source code on GitHub

Answer №2

The issue we are facing is that when executeAsyncScript is executed in the selenium-run browser, it does not transfer variables from the parent scope.

It seems challenging to find a solution for passing variables in this manner.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Interactive hexagon shape with dynamic image content on click using a combination of CSS, HTML,

As a beginner in CSS, HTML, and JavaScript, I came across a code snippet to create a pattern of hexagons with images (refer to the first code below). My goal is to change the image displayed on a clicked hexagon to another picture (see second code). First ...

What could be causing the error "SyntaxError: Expected token ']' to appear" to pop up?

Recently, I have been working on implementing a 'night mode' feature for a website. However, every time I attempt to execute the script, an error message pops up: "SyntaxError: Expected token ']'" on line 9. The problematic line in ...

Methods for dynamically adjusting content based on window width in Three.js

Currently, I have implemented a basic window resizing code in my project: function onWindowResize() { windowHalfX = window.innerWidth / 2; windowHalfY = window.innerHeight / 2; camera.aspect = window.innerWidth / window.innerHeight; came ...

Is there a way to save all the .hdf files on a website using Python?

import requests as rq r = rq.get('https://opendap.larc.nasa.gov/opendap/CALIPSO/LID_L15-Standard-V1-00/2019/01/contents.html', allow_redirects=True) open('CAL_LID_L15-Standard-V1-00.2019-01-01T00-25-44ZN.hdf', 'wb').write(r.co ...

It appears that Serverworker is causing significant delays in processing ajax requests

I'm encountering some performance issues with my PHP app that utilizes a lot of JavaScript for AJAX requests back to the PHP server. I'm currently implementing a service worker to cache content and enable push notifications, but I'm facing d ...

Pull data from another domain's DIV using jQuery's load/ajax function

I need to load content from a different domain into a DIV on my JSP page. For example: $("#myDiv").load("https://www.google.com") The issue I'm facing is that the request is being blocked by the browser's same origin policy. I've explore ...

The modal is functioning properly on Firefox and Internet Explorer, but it is experiencing issues

Having an issue with my modal not functioning properly in Chrome. When I click on it, only the background fades and both the before and after content load in the Chrome Dev tools simultaneously with no visible content in between. Here is a link to the Cod ...

Sort firebase information by chronological order based on timestamp

I'm currently working on sorting track IDs from firebase based on their timestamp (createdAt). The function is functioning correctly, but the ordering doesn't seem to work as expected. I'm not sure where the issue lies. Any assistance or sug ...

Is it possible to utilize a React component within the DataGrid cell instead of the standard cell types like 'string', 'number', 'date', and 'dateTime' in Material UI?

Using React, Material UI, and TypeScript I am trying to embed a React component into the cell of a DataGrid but have encountered an issue. I have explored custom column types for cells here, however, it only allows me to manage string formats, whereas I ...

What is the best way to display data in a React application depending on a boolean value?

Being new to React and JavaScript, I am currently struggling with boolean logic. I have a function called Profile which includes two constant methods that each return different data. function Profile(props) { const returnNormalProfile() const return ...

Submit button in a form using Selenium appears to not be working properly in Internet Explorer 11 after filling out input fields and choosing a dropdown option

In my dropdown menu, there is a form with 3 select dropdowns and 2 text inputs. The purpose of this form is to apply filters to a list of items. I can input text and make selections without using JavascriptExecutor by using .sendKeys("Text") for the text i ...

A guide on unpacking errors returned from a backend and sent out as an Error object in JavaScript

After investigating, it turns out that the issue lies with how the Error object constructor handles the response object passed to it in the catch error handler. The SDK I am using contains a method which can be found at this link to sdk code /** ...

Exploring Next.js: A Guide to Implementing Browsing History in Your Application

Struggling to add entries to browser history when using Next.js's Link property for page navigation. Unable to push history entry, leading to incorrect page location in my application when going back. Any ideas on implementing this feature in Next.js? ...

showing images received via a websocket connection

My current setup involves receiving one image per second through a WebSocket connection. The images are in blob format, and I am unsure of the best way to display them. Should I use an image tag or a video player? And how should I go about showing these ...

In search of a solution to automate video playback on Safari mobile with Appium

public WebDriver wd; @Test public void testSearchPage() throws InterruptedException { wd.get("http://live.viddigo.com/#/video/100496?_k=224w4e"); wd.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS); WebElement video= wd.findElem ...

What is the reason behind "Script" being considered the offspring of "Body"?

Unfortunately, I struggle with HTML/CSS/Javascript and am just trying to get through my exams. I have the code snippet below: <script> window.onload=function() { var c = document.body.childNodes; var txt = ""; var i; for ...

Troubleshooting: Datepicker not appearing in Bootstrap

Here is the detailed markup for the datepicker component: <div class="form-group row"> <div class="col-xs-3 col-md-offset-9"> <label class="control-label">Pick Date</label> <div class="input-group date" id="dp3" data-d ...

Can GET or POST variables be transmitted to external JavaScript?

Is it possible to pass a variable to an external JavaScript file? For instance: Suppose I have the following code: <script type="text/javascript" src="gallery.js"></script> I'm curious to know if it's feasible to pass an argument ...

Executing loop sequentially in Python

I am currently dealing with a block of code that is intended to crawl through websites of infinite height, like Facebook. The Python selenium script I have written requests the page's javascript to scroll down in order to load more content. However, d ...

Discover a non-null string within a deeply nested data structure

Within the 'task' object, the value of the 'door' property can vary each time it is accessed: var task = {}; task["123"] = [{"door":""}, {"door":""}, {"door":""}, {"door":""}]; task["456"] = [{"door":""}, {"door":"close"}, {"door":"" ...