Guide to creating a personalized matcher in Jasmine

Trying to create a Custom Matcher that checks for a specific number of occurrences of a particular string within another string. Here's my approach:

var customMatcher = {
    checkOccurrences: function (expectedString, expectedCount) {
        return {
            compare: function(actualString){
                actualString.match(new RegExp(expectedString, "g") || []).length == expectedCount;
            }
        }
    }
}

Encountering an error when running the code:

TypeError: Cannot read property 'pass' of undefined

The test setup looks like this:

expect(inputString).checkOccurrences("&", 2);

The expectation is for the input string to have exactly two occurrences of "&". What could be the issue here?

Answer №1

According to the documentation found on Jasmine's website:

The function used for comparison should return an object with a pass property that is a boolean indicating whether the matcher was successful (true) or unsuccessful (false).

Make sure to provide an object with these specific properties.

Give this code a try:

var customMatcher: {
    toContainTimes: function () {
        return {
            compare: function(actualValue, expectedResult){
                var expected = expectedResult[0];
                var num = expectedResult[1];
                var result = {
                    pass: true,
                    message: ''
                }
                result.pass = actualValue.match(new RegExp(expected, "g") || []).length === num;

                if(!result.pass)
                    result.message = 'Please insert error message here, which will be displayed when the Jasmine spec fails';

                return result;
            }
        }
    }
}

Usage:

expect(queryString).toContainTimes(["&", 2]);

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

Firefox not triggering image onload event

I have developed an image preloader that is functioning perfectly in all browsers except for Firefox (currently tested with version 10.0). Essentially, the input consists of an array of images named image_list. These images are dynamically appended to the ...

"Angular Ionic combination for displaying lists with customized headers and footers on cards

My issue is fairly straightforward - I am looking to create a list card with item array from my controller. However, I am struggling with how to structure my data in the HTML. The list card should have a header, content, and footer. I have attempted variou ...

Display/Conceal a div using CSS in React JS/Redux

I've been working on a CSS toggle for a div with className toggling. My approach involves using redux to manage the boolean state. Using the redux chrome extension, I can see that the state is indeed changing but the div remains invisible. If you have ...

Leverage multiple services within a single AngularJS controller

Is it possible to use multiple services in the same controller? Currently, I am able to achieve this with different services, but it seems to only perform one service. <!DOCTYPE html> <html> <script src="http://ajax.googleapis.com/ajax/libs ...

Ways to extract repeated value from a function?

Currently, I am working with two files. One file contains a script that generates a token, while the other file handles that token. The issue arises with the second script, as it only logs the initial token received and does not update with any new values ...

When using the updateMany function, only update the field if it already exists, without creating a new key

My goal within the $set operation is to update a field only if it already exists. While $cond seems to be on the right track, it has the drawback of always creating the field, which is not what I want. Filtering to retrieve only existing fields seems like ...

Divide text to reduce its width within the confines of a specific height on a div element

I've spent the past week scouring various forums, including stackoverflow, but I haven't been able to find a solution. In my responsive website, I'm using CSS flexbox to display dynamic menu items. Sometimes the text can be quite long, and ...

What could be causing my test to fail when it comes to an expectation within the `waitFor()` function?

My tests rely on the utility function below: async function waitForContentLoaded() { await waitFor(() => { expect(screen.queryByRole('progressbar')).not.toBeInTheDocument(); }); } Recently, I noticed that 2 out of my 37 tests are fail ...

How to use Python and JavaScript to make a WebElement visible in Selenium

I am currently facing an issue with uploading a PNG file using Selenium. The input element necessary for the upload process is visible to the user but not to Selenium. Following the suggestions in the Selenium FAQ, I tried using JavaScriptExecutor as shown ...

What is the best way to modify a variable in a nested element using ng-click in the parent element?

Review this code snippet: <section class="page-section about-us" scroll-bookmark="about-us" ng-click="activeSection=true" ng-init="activeSection=false"> <div class="page-content sub-content active-section">{{activeSection}} < ...

Is there a quick method to "install or fetch" for NodeJS?

I'm currently working on a piece of code that has the ability to proactively address missing dependencies without any need for manual intervention. What I envision is something along the lines of var aes256 = require_or_install('nodejs-aes256&ap ...

What is the process for filtering records by a date greater than in the Material Table?

How can I filter the Material table by date values greater than the current value? I've been able to filter by exact date so far, but I need to filter all values that are greater than or equal to the current value in the table. <TableMaterial ...

Trouble with AngularJS Smart Table when dealing with live data streams

Currently, I am facing a scenario where I am utilizing angularJs smart table for filtering. Here is the HTML code: <section class="main" ng-init="listAllWorkOrderData()"> <table st-table="listWorkOrderResponse"> <thead> ...

A guide to replacing or customizing standard components in ReactJS

I need to modify the color property of a common component so I can use it elsewhere. const ViewAllIcon = (props) => ( <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 26 ...

The useState setFunction does not alter on OnClick events

My useState element is causing issues because the function doesn't get called when I click on it. I've tried multiple solutions and debugging methods, but it seems like the Click event isn't being triggered no matter what I do. const [moda ...

How can I create a hover effect for a span element using html and css?

I have encountered an issue with hover color in span classes. I managed to successfully create two classes on this page, but the hover effect is not working on other classes. To troubleshoot, I included a link to my test page below. Can you please review i ...

Encountering difficulties importing in Typescript and ts-node node scripts, regardless of configuration or package type

I am facing a challenge with my React Typescript project where multiple files share a similar structure but have differences at certain points. To avoid manually copying and pasting files and making changes, I decided to create a Node script that automates ...

Stop and start an Express.js server using the original port number

Currently, my Node.js application utilizes Express.js to handle incoming connections. The code snippet looks something like this: const express = require("express"); var server = express(); server.get("/test", (req, res) => testResponse(req, res)); ser ...

What steps can be taken to align the description in the center of the div?

I am working on an image slider where the description slides in from left to right. My goal is to align the text justified and center it on the page. However, when I try adding CSS properties, it doesn't seem to have any effect. setting.$descpanel=$( ...

The options in the form select dropdown are not correctly positioned

I am new to using Jquery. I am attempting to create a submit form with a select option in it. However, the drop-down options are not displaying correctly. They appear slightly above and to the left of where they should be.https://i.sstatic.net/xZecM.png I ...