Loading go.js in testing environment

thanks Walter for your reply. I tried following your suggestion but i am getting below compile time error(Cannot read property ‘findNodeForKey’ of undefined on line 170). here is my complete java script. I am calling this script from my Java selenium code the way it was mentioned in earlier in this forum. please help.

var js = document.createElement("script");

js.type = "text/javascript";
js.src = "go.js";

var js1 = document.createElement("script");

js1.type = "text/javascript";
js1.src = "robot.js";


 var myDiagram;
 var robot;  // this global variable will hold an instance of the Robot class for myDiagram

    function init() {
      if (window.goSamples) goSamples();  // init for these samples -- you don't need to call this
      var $ = go.GraphObject.make;  // for conciseness in defining templates

      function showProperties(e, obj) {  // executed by ContextMenuButton
        var node = obj.part.adornedPart;
        var msg = "Context clicked: " + node.data.key + ". ";
        msg += "Selection includes:";
        myDiagram.selection.each(function(part) {
          msg += " " + part.toString();
        });
        document.getElementById("myStatus").textContent = msg;
      }

      function nodeClicked(e, obj) {  // executed by click and doubleclick handlers
        var evt = e.copy();
        var node = obj.part;
        var type = evt.clickCount === 2 ? "Double-Clicked: " : "Clicked: ";
        var msg = type + node.data.key + ". ";
        document.getElementById("myStatus").textContent = msg;
      }

     myDiagram =
        $(go.Diagram, "myDiagramDiv",  // must name or refer to the DIV HTML element
          {
            nodeTemplate:
              $(go.Node, "Auto",
                {
                  click: nodeClicked,
                  doubleClick: nodeClicked,
                  contextMenu:
                    $("ContextMenu",
                      $("ContextMenuButton",
                        $(go.TextBlock, "Properties"),
                        { click: showProperties })
                    )
                },
                $(go.Shape, "Rectangle",
                  { fill: "lightgray" },
                  { portId: "", fromLinkable: true, toLinkable: true, cursor: "pointer" }),
                $(go.TextBlock,
                  { margin: 3 },
                  new go.Binding("text", "key"))),
            model: new go.GraphLinksModel([
              { key: "Lambda" },
              { key: "Mu" }
            ], [
                { from: "Lambda", to: "Mu" }
              ]),
            "undoManager.isEnabled": true
          });

      // a shared Robot that can be used by all commands for this one Diagram
      robot = new Robot(myDiagram);  // defined in Robot.js

      // initialize the Palette that is on the left side of the page
      myPalette =
        $(go.Palette, "myPaletteDiv",  // must name or refer to the DIV HTML element
          {
            nodeTemplate: myDiagram.nodeTemplate,
            model: new go.GraphLinksModel([  // specify the contents of the Palette
              { key: "Alpha" },
              { key: "Beta" },
              { key: "Gamma" },
              { key: "Delta" }
            ])
          });
    }

    function dragFromPalette() {
      // simulate a drag-and-drop between Diagrams:
      var dragdrop = { sourceDiagram: myPalette, targetDiagram: myDiagram };
      robot.mouseDown(5, 5, 0, dragdrop);  // this should be where the Alpha node is in the source myPalette
      robot.mouseMove(60, 60, 100, dragdrop);
      robot.mouseUp(100, 100, 200, dragdrop);  // this is where the node will be dropped in the target myDiagram
      // If successful in dragging a node from the Palette into the Diagram,
      // the DraggingTool will perform a transaction.
    }

    function copyNode() {
      var alpha = myDiagram.findNodeForKey("Alpha");
      if (alpha === null) return;
      var loc = alpha.actualBounds.center;

      var options = { control: true, alt: true };
      // Simulate a mouse drag to move the Alpha node:
      robot.mouseDown(loc.x, loc.y, 0, options);
      robot.mouseMove(loc.x + 80, loc.y + 50, 50, options);
      robot.mouseMove(loc.x + 20, loc.y + 100, 100, options);
      robot.mouseUp(loc.x + 20, loc.y + 100, 150, options);
      // If successful, will have made a copy of the "Alpha" node below it.

      // Alternatively you could copy the Node using commands:
      // myDiagram.commandHandler.copySelection();
      // myDiagram.commandHandler.pasteSelection(new go.Point(loc.x+20, loc.y+100));
    }

    function dragSelectNodes() {
      var alpha = myDiagram.findNodeForKey("Alpha");
      if (alpha === null) return;
      var alpha2 = myDiagram.findNodeForKey("Alpha2");
      if (alpha2 === null) return;
      var coll = new go.Set();
      coll.add(alpha);
      coll.add(alpha2);
      var area = myDiagram.computePartsBounds(coll);
      area.inflate(30, 30);

      // Simulate dragging in the background around the two Alpha nodes.
      // This uses timestamps to pretend to wait a while to avoid activating the PanningTool.
      // Hopefully this mouse down does not hit any Part, but in the Diagram's background:
      robot.mouseDown(area.x, area.y, 0);
      // NOTE that this mouseMove timestamp needs to be > myDiagram.toolManager.dragSelectingTool.delay:
      robot.mouseMove(area.centerX, area.centerY, 200);
      robot.mouseUp(area.right, area.bottom, 250);
      // Now should have selected both "Alpha" and "Alpha2" using the DragSelectingTool.

      // Alternatively you could select the Nodes programmatically:
      // alpha.isSelected = true;
      // alpha2.isSelected = true;
    }

    function clickContextMenu() {
      var alpha = myDiagram.findNodeForKey("Alpha");
      if (alpha === null) return;
      var loc = alpha.location;

      // right click on Alpha
      robot.mouseDown(loc.x + 10, loc.y + 10, 0, { right: true });
      robot.mouseUp(loc.x + 10, loc.y + 10, 100, { right: true });

      // Alternatively you could invoke the Show Context Menu command directly:
      // myDiagram.commandHandler.showContextMenu(alpha);

      // move mouse over first context menu button
      robot.mouseMove(loc.x + 20, loc.y + 20, 200);
      // and click that button
      robot.mouseDown(loc.x + 20, loc.y + 20, 300);
      robot.mouseUp(loc.x + 20, loc.y + 20, 350);
      // This should have invoked the ContextMenuButton's click function, showProperties,
      // which should have put a green message in the myStatus DIV.
    }

    function deleteSelection() {
      // Simulate clicking the "Del" key:
      robot.keyDown("Del");
      robot.keyUp("Del");
      // Now the selected Nodes are deleted.

      // Alternatively you could invoke the Delete command directly:
      // myDiagram.commandHandler.deleteSelection();
    }

    function clickLambda() {
      var lambda = myDiagram.findNodeForKey("Lambda");
      if (lambda === null) return;
      var loc = lambda.location;

      // click on Lambda
      robot.mouseDown(loc.x + 10, loc.y + 10, 0, {});
      robot.mouseUp(loc.x + 10, loc.y + 10, 100, {});

      // Clicking is just a sequence of input events.
      // There is no command in CommandHandler for such a basic gesture.
    }

    function doubleClickLambda() {
      var lambda = myDiagram.findNodeForKey("Lambda");
      if (lambda === null) return;
      var loc = lambda.location;

      // double-click on Lambda
      robot.mouseDown(loc.x + 10, loc.y + 10, 0, {});
      robot.mouseUp(loc.x + 10, loc.y + 10, 100, {});
      robot.mouseDown(loc.x + 10, loc.y + 10, 200, { clickCount: 2 });
      robot.mouseUp(loc.x + 10, loc.y + 10, 300, { clickCount: 2 });
    }

clickLambda();

What compile-time error? JavaScript is interpreted.

You should remove the refernces to goSamples. Do you really want to refer to the DOM and Diagrams and model data of the Robot sample? You should be referring to your app’s diagrams and data.

I mean syntax error which I mentioned in my reply. I wanted to do quick
Proof of concept on sample GoJS app before moving to my application. Please help how should I unblock myself.

Sorry, we are completely unfamiliar with Selenium, so we cannot help you there.

But you might want to step through the code to see what is causing that error. My guess is that you haven’t initialized the diagram yet, which is why myDiagram is still undefined.

I am trying to automate https://gojs.net/latest/extensions/Robot.html and given my JS file which i am exeucting through java code and it is giving me Cannot read property ‘nodeDataArray’ of undefined error. How ever my Simple few lines of java script code is working fine and seleting the node.followed the same approach as given in this thread. please help.

 var s = document.createElement('script');
    s.type = 'text/javascript';
    s.async = true;
    s.src = 'c:\go.js'
    var x = document.getElementsByTagName('head')[0];
    x.appendChild(s);

   var k = document.createElement('script');
   k.type = 'text/javascript';
    k.async = true;
    k.src = 'C:\Robot.js'
    var x1 = document.getElementsByTagName('head')[0];
    x1.appendChild(k);


var myDiagram;
var robot;  // this global variable will hold an instance of the Robot class for myDiagram

    function init() {
      if (window.goSamples) goSamples();  // init for these samples -- you don't need to call this
      var $ = go.GraphObject.make;  // for conciseness in defining templates

      function showProperties(e, obj) {  // executed by ContextMenuButton
        var node = obj.part.adornedPart;
        var msg = "Context clicked: " + node.data.key + ". ";
        msg += "Selection includes:";
        myDiagram.selection.each(function(part) {
          msg += " " + part.toString();
        });
        document.getElementById("myStatus").textContent = msg;
      }

      function nodeClicked(e, obj) {  // executed by click and doubleclick handlers
        var evt = e.copy();
        var node = obj.part;
        var type = evt.clickCount === 2 ? "Double-Clicked: " : "Clicked: ";
        var msg = type + node.data.key + ". ";
        document.getElementById("myStatus").textContent = msg;
      }

      myDiagram =
        $(go.Diagram, "myDiagramDiv",  // must name or refer to the DIV HTML element
          {
            nodeTemplate:
              $(go.Node, "Auto",
                {
                  click: nodeClicked,
                  doubleClick: nodeClicked,
                  contextMenu:
                    $("ContextMenu",
                      $("ContextMenuButton",
                        $(go.TextBlock, "Properties"),
                        { click: showProperties })
                    )
                },
                $(go.Shape, "Rectangle",
                  { fill: "lightgray" },
                  { portId: "", fromLinkable: true, toLinkable: true, cursor: "pointer" }),
                $(go.TextBlock,
                  { margin: 3 },
                  new go.Binding("text", "key"))),
            model: new go.GraphLinksModel([
              { key: "Lambda" },
              { key: "Mu" }
            ], [
                { from: "Lambda", to: "Mu" }
              ]),
            "undoManager.isEnabled": true
          });

      // a shared Robot that can be used by all commands for this one Diagram
      robot = new Robot(myDiagram);  // defined in Robot.js

      // initialize the Palette that is on the left side of the page
      myPalette =
        $(go.Palette, "myPaletteDiv",  // must name or refer to the DIV HTML element
          {
            nodeTemplate: myDiagram.nodeTemplate,
            model: new go.GraphLinksModel([  // specify the contents of the Palette
              { key: "Alpha" },
              { key: "Beta" },
              { key: "Gamma" },
              { key: "Delta" }
            ])
          });
    }

    function dragFromPalette() {
      // simulate a drag-and-drop between Diagrams:
      var dragdrop = { sourceDiagram: myPalette, targetDiagram: myDiagram };
      robot.mouseDown(5, 5, 0, dragdrop);  // this should be where the Alpha node is in the source myPalette
      robot.mouseMove(60, 60, 100, dragdrop);
      robot.mouseUp(100, 100, 200, dragdrop);  // this is where the node will be dropped in the target myDiagram
      // If successful in dragging a node from the Palette into the Diagram,
      // the DraggingTool will perform a transaction.
    }

    function copyNode() {
      var alpha = myDiagram.findNodeForKey("Alpha");
      if (alpha === null) return;
      var loc = alpha.actualBounds.center;

      var options = { control: true, alt: true };
      // Simulate a mouse drag to move the Alpha node:
      robot.mouseDown(loc.x, loc.y, 0, options);
      robot.mouseMove(loc.x + 80, loc.y + 50, 50, options);
      robot.mouseMove(loc.x + 20, loc.y + 100, 100, options);
      robot.mouseUp(loc.x + 20, loc.y + 100, 150, options);
      // If successful, will have made a copy of the "Alpha" node below it.

      // Alternatively you could copy the Node using commands:
      // myDiagram.commandHandler.copySelection();
      // myDiagram.commandHandler.pasteSelection(new go.Point(loc.x+20, loc.y+100));
    }

    function dragSelectNodes() {
      var alpha = myDiagram.findNodeForKey("Alpha");
      if (alpha === null) return;
      var alpha2 = myDiagram.findNodeForKey("Alpha2");
      if (alpha2 === null) return;
      var coll = new go.Set();
      coll.add(alpha);
      coll.add(alpha2);
      var area = myDiagram.computePartsBounds(coll);
      area.inflate(30, 30);

      // Simulate dragging in the background around the two Alpha nodes.
      // This uses timestamps to pretend to wait a while to avoid activating the PanningTool.
      // Hopefully this mouse down does not hit any Part, but in the Diagram's background:
      robot.mouseDown(area.x, area.y, 0);
      // NOTE that this mouseMove timestamp needs to be > myDiagram.toolManager.dragSelectingTool.delay:
      robot.mouseMove(area.centerX, area.centerY, 200);
      robot.mouseUp(area.right, area.bottom, 250);
      // Now should have selected both "Alpha" and "Alpha2" using the DragSelectingTool.

      // Alternatively you could select the Nodes programmatically:
      // alpha.isSelected = true;
      // alpha2.isSelected = true;
    }

    function clickContextMenu() {
      var alpha = myDiagram.findNodeForKey("Alpha");
      if (alpha === null) return;
      var loc = alpha.location;

      // right click on Alpha
      robot.mouseDown(loc.x + 10, loc.y + 10, 0, { right: true });
      robot.mouseUp(loc.x + 10, loc.y + 10, 100, { right: true });

      // Alternatively you could invoke the Show Context Menu command directly:
      // myDiagram.commandHandler.showContextMenu(alpha);

      // move mouse over first context menu button
      robot.mouseMove(loc.x + 20, loc.y + 20, 200);
      // and click that button
      robot.mouseDown(loc.x + 20, loc.y + 20, 300);
      robot.mouseUp(loc.x + 20, loc.y + 20, 350);
      // This should have invoked the ContextMenuButton's click function, showProperties,
      // which should have put a green message in the myStatus DIV.
    }

    function deleteSelection() {
      // Simulate clicking the "Del" key:
      robot.keyDown("Del");
      robot.keyUp("Del");
      // Now the selected Nodes are deleted.

      // Alternatively you could invoke the Delete command directly:
      // myDiagram.commandHandler.deleteSelection();
    }

    function clickLambda() {
      var lambda = myDiagram.findNodeForKey("Lambda");
      if (lambda === null) return;
      var loc = lambda.location;

      // click on Lambda
      robot.mouseDown(loc.x + 10, loc.y + 10, 0, {});
      robot.mouseUp(loc.x + 10, loc.y + 10, 100, {});

      // Clicking is just a sequence of input events.
      // There is no command in CommandHandler for such a basic gesture.
    }

    function doubleClickLambda() {
      
      var lambda = myDiagramDiv.findNodeForKey(myDiagramDiv.model.nodeDataArray[0].key);
      alert("test");
      if (lambda === null) return;
      var loc = lambda.location;
     // windows.alert("clikc");
      // double-click on Lambda
      robot.mouseDown(loc.x + 10, loc.y + 10, 0, {});
      robot.mouseUp(loc.x + 10, loc.y + 10, 100, {});
      robot.mouseDown(loc.x + 10, loc.y + 10, 200, { clickCount: 2 });
      robot.mouseUp(loc.x + 10, loc.y + 10, 300, { clickCount: 2 });
    }

doubleClickLambda();

If you are going to load those JavaScript files asynchronously, you have to wait until they have finished loading. There should be some way to do that conveniently in your environment. Or just load them synchronously.

Are you calling init after the page has been laid out?

Are you calling a test function after the initialization has completed asynchronously?

Hi Davem, Followed your code and it is throwing error go is not defined. can u please share working code so that we can use. thanks in advance. I added referecne for go.js as well

Hi Walter, first page is getting loaded through java. After that i am able to select the node with the help of this code

            if (driver instanceof JavascriptExecutor) {
            String code = "var key = myDiagram.model.nodeDataArray[3].key;var node = myDiagram.findNodeForKey(key); myDiagram.select(node);"
                               + "  ";
            ((JavascriptExecutor) driver).executeScript(code);
            
            }

if i am able ot select the node means page is loaded. after this i want to click the selected code but code is not getting finalize. everywhere partial information is available. please help

I don’t know what to say, since I’m unfamiliar with your testing environment.

I suggest stepping through the code, debugging it in the browser, to see what has actually been executed and to see what the value of the various variables are.

Thanks Walter for your responses. I tried to do debugging in the chrome browser and it was giving error like : cannot load local resources so i included Robot.js using below code.

 var k = document.createElement('script');
   k.type = 'text/javascript';
   k.src = 'https://gojs.net/latest/extensions/Robot.js'  // Earlier it was pointing to local folder
   var x1 = document.getElementsByTagName('head')[0];
    x1.appendChild(k);

After adding this, i checked the browser->Sources and found that robot.js under extension folder. But still i am getting error like Robot is not defined on this url: https://gojs.net/latest/samples/basic.html

but same code worked fine and did mouse click on https://gojs.net/latest/extensions/Robot.html

please suggest what mistake i am doing.

When posting code in this forum, please surround your code with lines consisting of only triple backquotes. I have just edited your posts that way.

Don’t depend at run-time on resources that are not on and being served by your web server, unless they come from a CDN. That includes when testing. I don’t know what security problems that might causing.

Learn to debug your code in the browser. And regularly use browsers other than Chrome.

Thanks Walter for your response. I was manage to click on most of the sample canvas given in your portal but same code is not working on my application(after changing my canvas div is). Click is happening but it is not clicking on cordincates given by node. Is there any other way to get node cordinates?. I am really sorry to bother you so much.

Remember that all node coordinates are in document coordinates, not in view coordinates. https://gojs.net/latest/intro/viewport.html

I can help with GoJS-specific questions, but issues involving general debugging or testing are not our responsibility.