Invoke the built-in matcher within a Playwright custom matcher

I am in the process of implementing a custom matcher for Playwright based on the information provided in the official documentation on extending expect. In a similar vein to this unanswered discussion, my goal is to invoke an existing matcher after modifying the input:

expect.extend({
  async toHaveDeploymentURL(page: Page, expected: string) {
    const fullyQualifiedPath = `https://deployments.company.com${expected}`;

    // The issue lies here; trying to call an existing matcher 
    return expect(page).toHaveURL(fullyQualifiedPath);
  },
});

While browsing through a discussion on Jest issues, I came across a workaround to directly incorporate the Jest matchers:

import { getMatchers } from "expect/build/jestMatchersObject";

return expect.extend({
  toMatchEntity(actual, expected) {
    const copy = ... // object manipulation
    return getMatchers().toMatchObject.call(this, copy, expected);
  },
});

However, replicating this approach with Playwright matchers seems unfeasible as they are not exported in the package.json for @playwright/test.

Is there a different method to accomplish this task?

Answer №1

The initial code snippet is functional, however, the toHaveURL function returns undefined when successful, leading to an error:

Error: Unexpected return from a matcher function.
Matcher functions should adhere to the following format:
  {message?: string | function, pass: boolean}
'undefined' was returned

In this answer provided on a related query on Stack Overflow, it showcases how you can manage the successful return value yourself while also addressing the not condition. The revised example below functions correctly:

expect.extend({
  async toHaveDeploymentURL(page: Page, expected: string) {
    const matcher = this.isNot ? expect(page).not.toHaveURL : expect(page).toHaveURL;
    const fullyQualifiedPath = `https://deployments.company.com${expected}`;

    await matcher(fullyQualifiedPath);
    return {
      pass: true,
      message: () => `Deployment URL matched: ${expected}`
    };
  },
});

There seems to be ambiguity as to why undefined is returned in successful scenarios when observing the matcher source code. Nevertheless, it does generate a well-formatted error for situations where errors occur.

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

Using the currency pipe with a dynamic variable in Angular 2

My application utilizes CurrencyPipe, The current implementation is functional, <div class="price">{{123 | currConvert | currency:'USD':true:'3.2-2'}}</div> Now, I need to dynamically pass the currency from a model varia ...

Validating Inputs with an Array of Values in my Angular 2 Application

I have been exploring ways to retrieve data from an array of values instead of a single value when using [(ngModel)] binding in my Angular 2 application. The current setup functions perfectly with a single value, as shown below. The data is pulled from the ...

IDEA runs test successfully, however, when using maven the tests fail to complete

Currently, I am in the process of testing my application using Selenium WebDriver and TestNG. Within my codebase, there are a total of 15 methods that have been annotated with @Test. Interestingly, when I manually initiate the tests by right-clicking on th ...

Why does `react/require-default-props` still display an error even when a default prop value has been set?

This inquiry pertains to the guideline require-default-props. Here is the code snippet in question: function MyComponent({ blubb = 'my default', }: { blubb?: string, }) { // blubb defaults to 'my default' }; Eslint is flagging a ...

What could be causing my sinon test to time out instead of throwing an error?

Here is the code snippet being tested: function timeout(): Promise<NodeJS.Timeout> { return new Promise(resolve => setTimeout(resolve, 0)); } async function router(publish: Publish): Promise<void> => { await timeout(); publish(&ap ...

An issue occurred while trying to run Ionic serve: [ng] Oops! The Angular Compiler is in need of TypeScript version greater than or equal to 4.4.2 and less than 4.5.0, but it seems that version 4

Issue with running the ionic serve command [ng] Error: The Angular Compiler requires TypeScript >=4.4.2 and <4.5.0 but 4.5.2 was found instead. Attempted to downgrade typescript using: npm install typescript@">=4.4.2 <4.5.0" --save-dev --save- ...

Show detailed information in a table cell containing various arrays using AngularJS

After integrating d3.js into my code, I now have an array with key-value pairs. Each team is assigned a key and its corresponding cost is the value. When I check the console log, it looks like this: Console.log for key and value Rate for current month [{ ...

Error type inferred by TypeScript

I am currently in the process of learning TypeScript, and I encountered some errors in the code below: Error: Unexpected token. A constructor, method, accessor, or property was expected. [ts] Declaration or statement expected. class duckType{ public ...

Docz: Utilizing Typescript definitions for props rendering beyond just interfaces

We are currently using Docz to document our type definitions. While it works well for interfaces, we've run into an issue where rendering anything other than interfaces as props in Docz components doesn't seem to display properly. I'm seeki ...

Karma test encounters the absence of a defined Error Zone, causing an issue to

I have been encountering an error while trying to test a service in Angular. The error message reads: An error was thrown in afterAll Uncaught ReferenceError: Zone is not defined ReferenceError: Zone is not defined Despite visiting various forums and ...

Updates made in the type declaration files are not being displayed

I'm currently working on an express app and I have been trying to add a new property to the Request's class instance. To achieve this, I created a type.d.ts file at the root of my project that looks like this: type User = { name: string } de ...

What is causing my React-Testing Library queries to not work at all?

In my current project, I am using Jest along with Testing-Library to create UI unit tests. One issue that I encountered was that the components were not rendering on the DOM. After some investigation, I found that the main culprit was a component called & ...

Ensuring data integrity by validating incoming data with TypeScript and Angular 2

What is the best approach to validate data received from the server using AJAX or in a child component using the @input decorator in Angular2+ applications? In my current project, I utilize interfaces for this purpose, however they do not entirely valida ...

Tips for working with Typescript: utilizing the default value for a non-existent computed property

When utilizing Computed Property in javascript, I can structure my code as follows const default_values = {a:"debug",b:"info",c:"warning"}; function execute(y) { let x = default_values[y] || default_values.a /* if y is no ...

Leveraging moment.format Function in Angular within an HTML Context

Is there a way to implement the moment.format method in HTML? Currently, I am utilizing the toLocaleDateString method to showcase an array of dates: <ng-template let-event> <div>{{event.date.toLocaleDateString(' ...

The error that has occurred is: `TypeError: The object on the right side of the 'instanceof' keyword is

Testing my function that verifies if a variable is an instance of a specific type and performs an action has been successful. I conduct the verification using the following code: myCheckingFunction = () => { if (target instanceof H.map.Marker) { ... ...

Revamp the Next.js and TypeScript API for improved efficiency

I am new to using Next.js and TypeScript, and I would like to refactor my code to improve data fetching speed. Currently, I have a file called dashboard.tsx with the following code: import Layout from "@/layouts/layout"; import React, { useC ...

Dealing with name conflicts in Typescript when using multiple interface inheritance

Is it possible to securely implement two interfaces in Typescript that both have a member of the same name? Can this be achieved? For example: interface IFace1 { name: string; } interface IFace2 { name: string; } class SomeClass implements IFace ...

Tips for utilizing ngIf based on the value of a variable

Here is the code from my file.html: <button ion-button item-right> <ion-icon name="md-add-circle" (click)="save();"></ion-icon> </button> The content of file.ts is: editmode = false; I am trying to achieve the foll ...

The function ValueChange remains uninvoked

Query: The issue is that valueChanges is only triggered for the entire form and not for specific controllers. Although this approach works, it returns the complete object. public ngOnInit(): void { this.form.createWagonBodyForm(); ...