Unable to include custom matchers for Jasmine in an Angular project with Typescript

My current challenge involves adding multiple new custom matchers to jasmine and utilizing them effectively. I aim to create a file that registers 2 matchers, making all matchers readily available for each test file with just one registration.

In this case, I have a file called custom-matchers.ts

/// <reference path="custom-matchers.d.ts"/>

(() => {
  beforeEach(() => {
    jasmine.addMatchers({
      toHaveText: () => {
        return {
          compare: (actual, expected) => {
            return {
              pass: actual.getText().then(pass => pass === expected)
            };
          },
        };
      },
      toBePresent: () => {
        return {
          compare: (actual, expected) => {
            return {
              pass: actual.isPresent().then(pass => pass === expected),
            };
          },
        };
      }
    });
  });
})();

I also have a type definition file named custom-matchers.d.ts (I attempted using a different name than the references file but encountered the same issue):

declare namespace jasmine {
  interface Matchers<T> {
    toHaveText(text: any): boolean;
    toBePresent(text: any): boolean;
  }
}

This particular file is registered in another file named e2e-helper, which is then imported into every test file as e2e-helper.ts:

/// <reference path="custom-matchers.d.ts"/>
import './custom-matchers';

However, when attempting to use it in a test file, for example:

expect(object as any).toBePresent();

An error arises:

Property 'toBePresent' does not exist on type 'Matchers'

Answer №1

After some research, I discovered a workaround by importing the definition file in the helper file directly beneath the custom-matchers.ts file and giving it a unique import name. Here's how I did it:

import './custom-matchers';
import './custom-matchers-types'; // my custom definition file

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

Updating a behavior object array in Angular 5 by appending data to the end

After creating a service to share data across my entire application, I'm wondering if it's possible to append new data to an array within the userDataSource. Here is how the service looks: user.service userDataSource = BehaviorSubject<Array& ...

Is there a way to perform type narrowing within an Angular template?

I'm facing an issue with a component that requires a business object as an Input. Within the template of this component, I need to conditionally display some content based on the presence of a property that only exists in certain subclasses of the bus ...

I'm puzzled as to why my object remains static even after I reassign properties within a forEach loop

When retrieving an array of objects from an RX/JS call through an http backend, I encounter a peculiar issue. After making modifications to the object within a loop (attempting different methods like .forEach), the values seem to change temporarily but rev ...

Divide Angular module

In my Angular application, I have set up pages with a consistent header and sidebar structure. However, the main content on these pages may change based on different routes. To keep things organized, I decided to create a central page outlet where the main ...

The element 'mat-toolbar' is unrecognized and not known:

Encountering an issue while executing karma tests - the error message indicates that 'mat-toolbar' is not a recognized element within the application. Here are some steps to troubleshoot this problem: 1. Confirm whether 'mat-toolbar' is ...

Executing observables consecutively in Angular without delay

Here are the service calls that I have available: productService.GetAllProducts() productService.DeleteProduct() productService.GetCategories() productService.DeleteCategory() In pseudo code, I need to perform the following steps in my component: ...

Utilizing the most recent HTTP response from the previous request in Angular 8

Currently working with angular 8 and facing an issue on my list page with filters. Whenever a filter value is changed, it triggers an http request. The problem arises when users start changing the filters too frequently, causing multiple api requests to be ...

Exploring Geofirestore's capabilities with advanced query functionalities

Thinking about updating my firestore collection structure to incorporate geoquery in my app. Geofirestore requires a specific structure: interface GeoDocument { g: string; l: GeoPoint; d: DocumentData; } I understand that geofirestore does ...

In Angular 5, the term "this" denotes the Directive rather than the Component, particularly when transmitting a function from the component to the directive via @Input

Looking to create an autocomplete directive using angular. Check out this small demo I created for the issue: import { Component, NgModule, VERSION, Directive, Injectable, Input } from '@angular/core'; import { BrowserModule } from '@ang ...

What is the process for converting language json files into different languages?

I'm currently using ngx-translate to localize an Angular app. With over 20 languages that need translation, I am in search of a tool that can efficiently translate the language json files. While I did come across a helpful website, it proved to be ti ...

Using Systemjs with Angular 2 results in 50 server calls for loading resources

While following the Angular2 quickstart tutorial on Angular.io, I noticed that it was making 50 separate requests, which left me wondering why. https://i.sstatic.net/bqMk8.png Is there a way to consolidate all these requests into one? My goal is to have ...

Determining the location of the cursor within 'ng2-ckeditor'

I'm a beginner with Angular 2 and I'm using 'ng2-ckeditor 1.0.7' in my Angular 2 application. The editor is functioning well within the app. However, I am now faced with the challenge of appending text at the cursor position. Unfortunat ...

Simulate a series of user inputs using mock patches

Despite similar inquiries in the past, I am facing a challenge with a simple test that involves providing both a "y" and an "n" as inputs to a complex function that requires user interaction. My current attempt involves using a 'with' statement, ...

Utilizing TypeScript with Express.js req.params: A Comprehensive Guide

Having an issue with my express.js controller where I am unable to use req.params The error message being displayed is 'Property 'id' is missing in type 'ParamsDictionary' but required in type 'IParam'.' I need a w ...

adding new data rows to an existing data list using Angular

I am currently working on displaying data from a backend system. The data is coming from a table that receives new rows within a specific time frame. To retrieve these new rows, I have set up a mechanism using an Angular timer. My query pertains to the tem ...

Customize the theme type with @mui/system

Is there a way to customize my theme settings in @mui/system? While using the sx prop in Stack, the theme is defined in createTheme.d.ts, but it seems like there isn't an option to extend or override it. To work around this limitation, I have been u ...

Access the data within a jsonArray using Cypress

I'm dealing with a test.json file that contains a jsonArray [{ "EMAIL": "email_1", "FIRST_NAME": "Daniel" }, [{ "EMAIL": "email_2", "FIRST_NAME": "John" }] ] I'm trying to figure out how to use cypre ...

Issues with error handling in Angular 7 causing unexpected behavior

Encountering issues with 422 error handling in my HTTP request. The error block is not executing as expected when using the catchError operator in the service. If no errors occur, the code functions properly. However, I need to show an error message on the ...

Keep the Angular Material tables refreshed with the latest data pulled from an API

In my Angular application, I have implemented a table using Angular Material and populated it with data retrieved from an API. The relevant code snippet is as follows: ngOnInit() { this.getChillerApiData(); } getChillerApiData() { this.api. ...

Instructions for updating an entire object within an array using Mongoose

I am currently working with Mongoose and Typescript, and my document structure is as follows: { _id: 1, id: "a", markets: [{ type: "car", price: 10000}, {type: "toy", price: 10},...] ...