Having trouble achieving success with browser.addcommand() in webdriverIO using typescript

I tried implementing custom commands in TypeScript based on the WebdriverIO documentation, but unfortunately, I wasn't able to get it working.

my ts.confg
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "*": [
        "./*"
      ],
      "src/*": [
        "./src/*"
      ],
      "test/*": [
        "./test/*"
      ]
    },
    /* Basic Options */
    // "incremental": true, 
    "sourceMap": true,
    "outDir": "out",                          /* Enable incremental compilation */
    "target": "es6",                         
    "module": "commonjs",  
"typeRoots": ["./types"],                       /* List of folders to include type definitions from. */
    "types": [
      "node",
      "@wdio/sync",
      "@wdio/jasmine-framework"
   ],                           
    "esModuleInterop": true,                    

  "include": ["./test/**/*.ts","./types/wdio.d.ts","./types/command.ts"],
  "exclude": [
    "./node_modules"
  ],
}

The types file contains wdio.d.ts declarations.

declare module WebdriverIO {
  interface Element {
    waitAndClick: () => void;

  }
  interface Browser {
    // waitAndClick: (el:WebdriverIO.Element) => void;
    // you can add commands here too
    // waitAndClick: () => void;

  }
}

In my wdio.conf.js file:

before: function (capabilities, specs) {
        browser.addCommand('waitAndClick', ()=> {
            var el = $();
            el.waitForDisplayed({timeout: 5000});
            el.click();
        }, true);
       }

And in my spec file:

$('mat.classname').waitAndClick();

However, I'm still getting an error that says "Error: selector needs to be typeof string or function".

Answer №1

Here is where the error originates in the code:

var el = $();

The WDIO notifies you about this because no selector is being passed.

To correctly implement your custom command, use the following code:

browser.addCommand("waitAndClick", function () {
    this.waitForDisplayed({timeout: 5000})
    this.click()
}, true)

When calling waitAndclick on an element (

$('mat.classname').waitAndClick()
), this will refer to the element and allow you to execute your custom command on it.

Note: Avoid using arrow functions in your custom command in this scenario, as it will not reference the correct context:

browser.addCommand("waitAndClick", function () {

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

Enabling a mat-slide-toggle to be automatically set to true using formControl

Is there a way to ensure that the mat-slide-toggle remains true under certain conditions? I am looking for a functionality similar to forcedTrue="someCondition". <mat-slide-toggle formControlName="compression" class="m ...

Troubleshooting: Issues with Angular2 compatibility on Safari version 9.1.2

I am encountering an issue with running my angular2 app on Safari 9.1.2. It works fine on all higher versions of Safari as well as other browsers such as Chrome, Firefox, Opera, and Edge. However, when I try to run it on Safari 9.1.2, I receive the followi ...

Can Material UI be defined as a peerDependency while maintaining its types as a DevDependency?

Is there a way to set Material UI as a peerDependency while keeping its types as DevDependency? I'm currently working on a component library using React + Typescript, with components based on Material UI and Rollup as the module bundler. For example ...

The data type 'string | undefined' cannot be assigned to the data type 'string' when working with .env variables

Trying to integrate next-auth into my nextjs-13 application, I encountered an error when attempting to use .env variables in the [...nextauth]/route.ts: Type 'string | undefined' is not assignable to type 'string'. https://i.stack.im ...

Exploring the Possibilities of Nipplejs Integration in Vue with Quasar

Trying to implement Nipplejs in my Vue Project using quasar Components. Installed nipplejs through npm install nipplejs --save. Attempted integration of the nipple with the code snippet below: <template> <div id="joystick_zone">&l ...

Can you explain the mechanics behind the functionalities of @angular and @type dependencies?

This inquiry may have been raised before, but I couldn't uncover all the solutions. If that's the case, my apologies. I have a good grasp on how package.json and dependencies / dev-dependencies function in Node applications. Currently delving i ...

Turn off the interconnected route while utilizing npm to display the tree of dependencies

If I want to display the project's dependencies tree using npm, I would use the following command: npm ls lodash The output will look something like this: > npm ls lodash npm info using [email protected] npm info using [email protected] ...

Exploring various queries in Firestore

Does anyone know if there is a way to create a sentence similar to this one: return this.db.collection('places', ref => ref.where("CodPais", "<>", pais)).valueChanges(); I have tried using != and <> but neither seem to be valid. Is the ...

failure to render updated content after modification of variable

I am facing an issue with triggering a function in the component: componentA.ts html = 'hey'; this.onElementSelected(r => this.change()); public change() { console.log(this.html); if (this.html === 'hey&ap ...

Remove all `Function.prototype` methods from Typescript

Can a callable object (function) be created without utilizing Function.prototype methods? let callableObject = () => 'foo' callableObject.bar = 'baz' callableObject() // 'foo' callableObject // {bar: 'baz'} call ...

Error: Type '() => () => Promise<void>' is not compatible with type 'EffectCallback'

Here is the code that I'm currently working with: useEffect(() => { document.querySelector('body').style['background-color'] = 'rgba(173, 232, 244,0.2)'; window.$crisp.push(['do', 'ch ...

Use Node.js with Selenium and WebdriverIO to simulate the ENTER keypress action on

I have put in a lot of effort trying to find the solution before resorting to asking this question, but unfortunately I have not been successful. All I need to know is how to send special characters (such as the enter key and backspace) with Node.js using ...

What is the best way to sort through this complex array of nested objects in Typescript/Angular?

tableData consists of an array containing PDO objects. Each PDO object may have zero or more advocacy (pdo_advocacies), and each advocacy can contain zero or more programs (pdo_programs). For example: // Array of PDO object [ { id: 1, ...

Unable to utilize the namespace 'RouteComponentProps' as a specified type

When using TypeScript to define an interface that extends RouteComponentProp, I encountered some issues: VSCode error: [ts] Cannot use namespace "RouteComponentProps" as a type. Console error: Cannot use namespace 'RouteComponentProps' as a typ ...

Handling HTTP errors in Angular when receiving a JSON response

I'm struggling to resolve this issue and I've searched online with no luck. The problem lies in my post call implementation, which looks like this: return this.http.post(url, body, { headers: ConnectFunctions.getHeader() }).pipe( map(result =&g ...

Bringing in a module that enhances a class

While scouring for a method to rotate markers using leaflet.js, I stumbled upon the module leaflet-rotatedmarker. After installing it via npm, I find myself at a loss on how to actually implement it. According to the readme, it simply extends the existing ...

Utilizing External Libraries Added Through <script> Tags in React

My goal is to develop a Facebook Instant HTML5 application in React. Following their Quick Start guide, Facebook requires the installation of their SDK using a script tag: <script src="https://connect.facebook.net/en_US/fbinstant.6.3.js"></scrip ...

Referring to TypeScript modules

Consider this TypeScript code snippet: module animals { export class Animal { } } module display.animals { export class DisplayAnimal extends animals.Animal { } } The objective here is to create a subclass called DisplayAnimal in the dis ...

Is it possible for the Chrome debugger to locate TypeScript files that have not been served by the

I am creating .js.map files to assist in debugging my TypeScript code within Chrome. The js.map files specify the correct location of the TypeScript in the "sources" property. sourceRoot is set to "", and sources represent the path to the TypeScript code ...

Picking up Angular component property values within a callback function from Google Charts

Trying to utilize the angular-google-charts library in Angular 13.2, I am working on creating a TreeMap with a customized tooltip feature. The GoogleChartComponent offers an options property called generateTooltip which requires a callback function. My goa ...