Search code examples
angulartypescriptprotractorangular2-directivese2e-testing

How to access and manipulate structural directives during an e2e test


Background: I want to be able to permutate all possible configurations of an Angular2 screen for a given route and screenshot them using Protractor: http://www.protractortest.org/#/debugging.

Issue: I can't seem to find a way to acces a directive (like ng-if for example) during an e2e Test.

  • Is it possible to access the ng-if directive inside of an e2e test?
    • If yes: is there a way to manipulate the directive? By manipulate i mean to influence the evaluation of the directive without changing the input on which the directive depends.

Possible solution path: here is an example on how i acces the router to be able to navigate to a specific route:

it('should get the router', () => {
browser.executeScript(() => {
  const ng = window['ng'];
  const root = document.getElementsByTagName('app-root')[0];
  const router = ng.probe(root)
    .injector.get(ng.coreTokens.Router);
  const routes = router.config;
  ...
  ...
  return [];
}).then(ret=> console.log(ret));
});

Thoughts:

  • Maybe it is possible to somehow get the ng-if directives using ng.probe

I would apreciate any hints regarding my question.


Solution

  • You can do it as follows:

    html

    <button id="find">Find ngIf directives and show all</button>
    

    script

    var findComments = function(el) {
        var arr = [];
        for(var i = 0; i < el.childNodes.length; i++) {
            var node = el.childNodes[i];
            if(node.nodeType === 8) {
                arr.push(node);
            } else {
                arr.push.apply(arr, findComments(node));
            }
        }
        return arr;
    };
    
    
    function findNgIfDirectives() {
      var commentNodes = findComments(document);
      const ng = window['ng'];
      commentNodes.forEach(function(node) {
        var debugNode = ng.probe(node);
        var ngIf = (debugNode.providerTokens[0]);
        var ngIfInstance = debugNode.injector.get(ngIf);
    
        ngIfInstance.ngIf = true;
      });
    
    }
    document.getElementById('find').addEventListener('click', findNgIfDirectives)
    

    Plunker Example