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

At what point is it appropriate for a class to incorporate an interface?

Currently working on a project and I've noticed developers using TypeScript in the following way: export class Ledger implements ILedger { LedgerID: number; CashAmmount: number; Units: number; ...

Indeed, conditional validation is essential

I have encountered an issue with my schema validation where I am trying to validate one field based on another. For example, if the carType is "SUV", then the maximum number of passengers should be 6; otherwise, it should be 4. However, despite setting u ...

Changes in the styles of one component can impact the appearance of other

When it comes to styling my login page, I have specific stylesheets that I include in login.component.ts. For all the common CSS files, I have added them in the root index ("index.html") using the traditional method. However, after a user logs into the sys ...

The TypeScript compiler is unable to locate the name 'window'

Within my Meteor/React project, I encounter the following line of code: let gameId = window.prompt("Please input the ID of the game you would like to load."); The TypeScript compiler presents an error during transpiling: Cannot find name 'window&apo ...

Experimenting with Nuxtjs application using AVA and TypeScript

I'm in the process of developing a Nuxt application using TypeScript and intend to conduct unit testing with AVA. Nonetheless, upon attempting to run a test, I encounter the following error message: ✖ No test files were found The @nuxt/typescrip ...

The JokesService (?) has encountered dependency resolution issues that Nest is unable to resolve

Currently delving into the world of NestJS and feeling a bit perplexed about the workings of "modules". In my project, I have two modules namely JokesModule and ChuckNorrisApiModule. My goal is to utilize the service provided by ChukNorrisService within th ...

Testing React Components - The `useClient` function should only be used within the `WagmiConfig` component

In my Next.js app with TypeScript, Jest, and React testing library, I encountered an error while trying to test a component. The error message states that `useClient` must be used within `WagmiConfig`. This issue arises because the `useAccount` hook relies ...

What are the drawbacks of introducing a dependency within the constructor?

I'm struggling to understand why breaking the rules is considered bad. import {DepClass} from './di-import' // <- some dependency imports here class DI1 { dep1: DepClass constructor(){ this.dep1 = new DepClass() // ...

Beginner - managing tasks with React and TypeScript

Can someone assist me with a minor issue? I have experience programming in React using pure JavaScript, but I'm struggling with transitioning to TypeScript. I don't quite understand all the hype around it and am finding it difficult to work with. ...

How to set up an Angular ErrorHandler?

Attempted to register an Angular ErrorHandler in this simplified StackBlitz environment, but it seems that it's not capturing the error thrown within the constructor of the HelloComponent. Any insights on this issue? Your opinions? ...

What is the best way to utilize the Moment.js TypeScript definition file in a website that already has moment.min.js integrated?

Currently, I am in the process of transitioning a website to utilize TypeScript by converting one JavaScript file at a time. All pages on my site are already linked to moment.js, such as: <script src="/scripts/moment.min.js"></script> I have ...

What steps are involved in launching an outdated Angular project?

Tasked with reviving an old Angular client in my company, I found myself grappling with outdated files and missing configurations. The lack of package.json, package-lock.json, and angular.json added to the confusion, while the presence of node modules in t ...

Are your custom guards failing to function properly now?

Previously, the code below was functioning properly until typescript 2.0: class Aluno{ escola: string; constructor(public nome: string){ this.escola = ""; } } class Pessoa{ morada: string; constructor(public nome: string){ this.morada = ...

Submitting a form using an anchor tag in Angular 8: A step-by-step guide

I have a question about how to submit form data using hidden input fields when a user clicks on an <a> tag. <form action="/submit/form/link"> <input type="hidden" [attr.value]="orderNumber.id" /> <input type="hidden" [attr.value]= ...

Understanding how to extract an enum from a string and its corresponding value in TypeScript

I am working with a simple enum called errorCode, shown below: export enum SomeErrorCodes { none = 0, notFound = 1, duplicated = 2 } Currently, I am receiving the name of the enum as a string "SomeErrorCodes" and a number, for example, 1. How ...

Tips for altering a key within a tree-view:

I am working with a potentially infinite tree-view array: type Tree = { id: number; name: string; email: string; children: Tree[]; }; const tree: Tree[] = [ { id: 1, name: 'Truck', email: '@mail', children ...

When compiling in Visual Studio 2019, the process terminated with exit code -1073741819

Today, upon returning to my asp .net core-project with react and typescript as front end, I encountered an error message after running the "Build" command. Can anyone shed some light on what this error means and how it can be fixed? Severity Code De ...

The IDBCursor type does not have a property named 'value'

It appears that the typescript typings are not aware of the value property on the IDBCursor interface. let cursor: IDBCursor; cursor.value ...

What is the best way to retrieve data from MySQL for the current month using JavaScript?

I need to retrieve only the records from the current month within a table. Here is the code snippet: let startDate = req.body.startDate let endDate = req.body.endDate let result = await caseRegistration.findByDate({ p ...

Looking to display parent and child elements from a JSON object using search functionality in JavaScript or Angular

I am trying to display both parent and child from a Nested JSON data structure. Below is a sample of the JSON data: [ { "name": "India", "children": [ { "name": "D ...