3

I am trying to use jQuery selectors with my Nightwatch.js e2e tests According to this answer :

How to write a nightwatch custom command using jquery

I need to have jQuery available in the global scope of my app for this to work. ( otherwise I got into trouble with $(selector) refs ...

'use strict';

var ClickElementByIndex = function(className, index) {
  if (!index) {
    index = 0;
  }

  this.execute(function(selector, i) {
    var $item = $(selector + ':eq(' + i + ')');
    if (!!$item) {
      $item.click();
      return true;
    }
    return false;
  }, [className, index], function(result) {
    console.info(result);
  });
};

exports.command = ClickElementByIndex;
  • duplicated question see answer. at https://stackoverflow.com/questions/21674080/how-to-use-npm-jquery-module –  Oct 11 '17 at 07:34

1 Answers1

1

You just need to add the jquery package as a dependency to your package.json and then you must require jquery within the file. Typically, you would have already done this for nightwatch. To add the package, jquery, as a dep, run this command from the root directory of your project:

npm install jquery --save-dev

Then verify it worked by checking that you have an additional line added for jquery to package.json. It will look like this:

"devDependencies": { "jquery": "^3.2.0",

Note: If no package.json exists yet, go to the top level folder in the project and run npm init. After going through the prompts, you can add both jquery and nightwatch as dev-deps using the above command.

Lastly, to require jquery in your custom command or assertion, just add const $ = require('jquery') to the top of the file to assign $ as jquery.

enphnt
  • 88
  • 8