Issue with Jasmine test: function is not being executed

Currently, I am testing a validator that involves making a call to a service. If the call returns zero, an error object is returned.

I have successfully created a spy for the service and used returnValue, which seems to be working well. However, I am facing challenges when it comes to executing the validation function and returning the value.

To solve this issue, I resorted to creating a spy for the function I am testing, although I believe this might not be the correct approach.

This is the validator function:

It takes a service as a parameter and utilizes it internally

static require(service: Service): ValidatorFn {
   return (formGroup: FormGroup): { [key: string]: boolean } | null => {
      const checkedCount = state.currentCount();
      if (checkedCount === 0) {
          return  {
            'isNotChecked' : true
          };
        }
      return null;
    };
  }

The successful test case is as follows: I am unsure whether spying on the function under test is the appropriate method?

  it('should return error object when currentCount === 0', () => {
        spyOn(service, 'currentCount').and.returnValue(0);
        spyOn(ModValidation, 'require').and.returnValue({ 'isNotChecked' : true });
        service.currenCount();
        expect(ModValidation.require(service)).toEqual({ 'isNotChecked' : true });
    });

My unsuccessful attempt is shown below:

  it('should return error object when currentCount === 0', () => {
        spyOn(service, 'currentCount').and.returnValue(0);
        const resp = ModValidation.require(service);
        service.currentCount();
        expect(resp).toEqual({ 'isNotChecked' : true });
    });

Upon running this failed test, I encountered the following output:

Expected Function to equal Object({ isNotChecked: true }).

Answer №1

When using the require method within the validator, it's important to note that this function transforms an AbstractControl into a validation result.

To properly call this method, you should use something similar to the following:

it('currentCount 0', () => {
    const service = {currentCount: () => {}};
    spyOn(service, 'currentCount').and.returnValue(0);

    expect(CustomValidators.require(service)({} as any)).toEqual({
            'isNotChecked' : true
          });
  });

Feel free to check out the Stackblitz I created for more information: stackblitz

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

Step-by-step guide for setting up automatic Tslint in IntelliJ

When working on an Angular project in Intellij, I often encounter numerous tslint errors while coding. Is there a command within Intellij that can automatically fix all of these lint errors? ...

GraphQL queries that are strongly-typed

Currently working on a Vue CLI project where I am utilizing axios as my request library. In all the examples I've come across, they use strings for queries like this: { hero { name friends { name } } } Given that I am employing ...

Ways to store a component in cache once its route is triggered

There are 3 components in my project: 1 parent and 2 child components with router outlet. The child component becomes active whenever its route is called, sharing data using a service. Both of these child components have complex views. When switching bet ...

Understanding the integration of sass with webpack in an Angular 4 project

Is it possible to reference a sass file instead of a css file directly in the index.html? If so, how does webpack compile the sass into a css file? Additionally, what is the most effective way to bundle the sass file when building the application? The ve ...

Determining the type of index to use for an interface

Imagine having an interface called Animal, with some general properties, and then either be a cat or a dog with corresponding properties. interface Dog { dog: { sound: string; } } interface Cat { cat: { lives: number; } } type CatOrDog = Cat | D ...

Creating a global variable using Typescript in AngularJS components

Within my application, I have been utilizing components and a boostrapper. The main goal is to implement a datepicker that can set a global date variable. Despite exploring various options such as creating a service, utilizing rootscope, and researching so ...

Creating a React TypeScript component that utilizes two distinct prop interfaces

I'm trying to develop a React TypeScript component that combines two different interfaces in its props. However, I keep encountering the following warning: TS2339: Property 'color' does not exist on type 'PropsWithChildren<Props> ...

Utilizing React and TypeScript: managing component states with arrays

In the TypeScript code below, I have a React component called Foo: import * as React from 'react' import * as ReactDOM from 'react-dom' interface FooProps { name: string } interface FooState { name: string } export class Foo ...

Creating a unique custom complex template typeahead implementation with Angular 2 and Ng2-Bootstrap

I encountered an issue with the ng2-bootstrap typeahead implementation and have created a plunker to demonstrate the problem. Check out the plunker example here <template #customItemTemplate let-model="item" let-index="index"> <h5>This is ...

Tips for implementing collapsible functionality that activates only when a specific row is clicked

I need to update the functionality so that when I click on a row icon, only that specific row collapses and displays its data. Currently, when I click on any row in the table, it expands all rows to display their content. {data.map((dataRow ...

How can I utilize the Redux store outside of a component in a React application with ASP.NET Core and TypeScript?

While I have some experience with React, I am new to using Redux. Luckily, Visual Studio 2017 comes with a built-in template for React + Redux under .NET Core 2.0. About my environment: Visual Studio 2017 React 15.6.1 TypeScript 2.4.1 Redux 3.7.1 Rea ...

Uncaught Error: Unable to access 'visit' property of null

Sharing this in case it helps someone else who encounters the same error, as the stack trace doesn't offer any clues on what might have caused the problem. ...

Angular's Not In operator can be used to filter out unwanted

As a newcomer to Angular, I am attempting to implement a basic if statement to verify that my property does not match one of 10 specific values. Is there a method or filter within enums or lists that can achieve this easily? public type: string; if(type = ...

Facing unexpected behavior with rxjs merge in angular5

import { Observable } from 'rxjs/Observable'; import 'rxjs/add/observable/merge'; this.data = this.itemsCollection.valueChanges() this.foo = this.afs.collection<Item>('products') .doc('G2loKLqNQJUQIsDmzSNahlopOyk ...

implementing an event listener in vanilla JavaScript with TypeScript

Can anyone help me figure out how to correctly type my event listener in TypeScript + Vanilla JS so that it has access to target.value? I tried using MouseEvent and HTMLButtonElement, but I haven't been successful. const Database = { createDataKeys ...

When running the npm install command for Angular, an error occurred stating: "npm ERR! Maximum call stack

Upon running npm install, I encountered the following message: npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2256510f514b4f524e470f4351566213100c160c12">[email protected]</a>: NOTICE: ts-si ...

Declaration of function with extra attributes

Is there a way to define a type for a function that includes additional properties like this? foo({ name: 'john' }) foo.type I tried the following solution, but TypeScript seems to think that foo only returns the function and cannot be called wi ...

Tips for Embedding an External Website within an Angular Page without Using Web Elements

How can I create a global navigation that opens different apps on each nav link click, regardless of the technology they are built on? The challenge is that the navigation is in Angular and while we can integrate apps using Angular web elements if they a ...

Adding "assets" to the ng-package.json file with ng-packagr does not apply global styles to an Angular library

I'm currently working on an Angular library (version 9.1.11) with Storybook and I'm looking to apply styles globally. I am aware that for versions 9.x and above of ng-packagr, it is possible to include assets in your library package during the bu ...

Why is the MEAN stack DELETE function failing to work properly? Could the issue be related to

My Angular4, Express 4.15 and Node 7.9 setup is working well with GET, POST, PUT requests. However, I'm facing an issue with the delete function. I am using Mlab for my MongoDB and connecting through mongojs. Edit - When sending a DELETE request via ...