2

Is it possible to execute jQuery commands from Angular e2e scenario ?

for example, if I would like to execute : $('.picker-col-id-id').attr('class'); I'm getting an error:

TypeError: Property '$' of object [object Object] is not a function

Agustin Meriles
  • 4,866
  • 3
  • 29
  • 44
Igal
  • 4,603
  • 14
  • 41
  • 66

2 Answers2

11

The problem here is that the AngularJs Scenario Test Runner runs your application in an iframe. The runner itself hasn't loaded jQuery.

It's best to use the angular scenario dsl. From the e2e testing docs:

element(selector, label).{method}(key, value)

Executes the method passing in key and value on the element matching the given jQuery selector, where method can be any of the following jQuery methods: attr, prop, css. The label is used for test output.

Although not clear from the docs, you can also use the 'attr' method with only 1 argument to get the value of the attribute.

element('.picker-col-id-id').attr('class');

If you need other jQuery functionality, like focus(), you can do it this way:

element('.picker-col-id-id').query(function(elements, done) {
    elements.focus();
    done();
});

Or extend the angular dsl

angular.scenario.dsl('jQueryFunction', function() {
    return function(selector, functionName /*, args */) {
        var args = Array.prototype.slice.call(arguments, 2);
        return this.addFutureAction(functionName, function($window, $document, done) {
            var $ = $window.$; // jQuery inside the iframe
            var elem = $(selector);
            if (!elem.length) {
                return done('Selector ' + selector + ' did not match any elements.');
            }
            done(null, elem[functionName].apply(elem, args));
        });
    };
});

And use it this way:

jQueryFunction('.picker-col-id-id', 'focus');

Or in general:

jQueryFunction(selector, jQueryFunctionName, arg1, arg2, ...);
Jeroen V.
  • 111
  • 3
1

As mentioned in the comments it looks like jQuery is missing. You will need to add it, either to your karma configuration file or directly to runner.html.

If you want to add it to your karma config file augment the files entry to add a reference to jQuery, e.g.,

files = [
  ANGULAR_SCENARIO,
  ANGULAR_SCENARIO_ADAPTER,
  'app/components/jquery/jquery.js', // <== This should point to jQuery
  'test/e2e/**/*.js'
];

Alternatively, if you're running your e2e tests from runner.html you could load it there, after angular and before your script, e.g., :

<!doctype html>
<html lang="en">
   <head>
      <title>End2end Test Runner</title>
      <script src="../lib/angular/angular-scenario.js" ng-autotest></script>
      <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
      <script src="scenarios.js"></script>
   </head>
   <body>
   </body>
</html>
lorcan
  • 3,280
  • 3
  • 24
  • 31