What steps are involved in generating a FormGroup identical to the one produced by the method?

Implementing a FormGroup within the context of a Mat Dialog window, I am aiming to validate the method that returns the FormGroup through unit tests.

The method triggered on button click is as follows:

closeDialogAndSendForm(): void {
    this.dialogWindow.close(this.form)

}

My unit test scenario involves (I have set up a form with just one field for testing purposes):

it('should close dialog and return FormGroup', fakeAsync(async () => {
    await selectAnswers();
    let resultFormGroup = createResultFormGroup();
    let spy = spyOn(component.dialogWindow, 'close');
    flush();
    fixture.detectChanges();
    clickOnButton('SUBMIT', fixture);
    expect(spy).toHaveBeenCalledWith(resultFormGroup);
}));

In the function createResultFormGroup(), my intention is to generate an identical form structure as the one returned by the previously mentioned method:

function createResultFormGroup(): FormGroup {
    let form = new FormGroup({testField: new FormControl(true, Validators.required)});
    return form;
}

However, upon running the test, multiple discrepancies arise such as the ones stated below:

Call 0:
  Expected $[0]._onCollectionChange = Function to equal Function.
  Expected $[0].pristine = false to equal true.
  ...
Error: Expected spy close to have been called with:

Is there any way to mock this behavior or should I focus solely on comparing field names and values?

Answer №1

There seems to be a discrepancy in the code between the expected FormGroup and the actual FormGroup returned by the method. One approach is to compare only the field names and values, or alternatively, you can create a mock FormGroup object that closely resembles the expected object.

To create a mock FormGroup object, you can use the FormGroup constructor with an object containing the same field names and initial values as the expected object. For instance:

const expectedFormGroup = new FormGroup({
  testField: new FormControl(true, Validators.required)
});

// Create a mock FormGroup with matching field names and values
const mockFormGroup = new FormGroup({
  testField: new FormControl(true, Validators.required)
});

// Compare the mock FormGroup with the actual FormGroup
expect(spy).toHaveBeenCalledWith(mockFormGroup);

This approach can assist you in testing the method effectively and ensuring its functionality.

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

What could be the possible reason for the token having a null value during login authentication in

As a beginner to Angular, I am facing an issue with my JWT login page implementation. Despite printing the token in the console and confirming its existence as a string, I am receiving a null (or undefined) value. This is the code snippet from my UserServi ...

Creating a custom enum using generics in TypeScript can be excessively intricate

Is there a simpler way to streamline this code? It feels very repetitive and not quite right... const FolderVisibility = new Enum<{ PUBLIC: 'public', PRIVATE: 'private' }>({ PUBLIC: 'public', PRIVATE: &a ...

Persuade TypeScript to trust that all necessary keys will be present in an object

I find myself in this particular scenario: const user: UserObj = User.get(userId); if ([user.foo, user.bar, user.baz].some((k) => !k)) throw new Error(`Missing fields for user ${userId}`); const createParams: CreateParams = { firstName: user.first ...

Trouble encountered with Angular Google Maps integration when using router-outlet

Currently, I am in the process of developing an application that features a map as its header (providing a global view) and another map positioned in the center of the page to showcase detailed views. To demonstrate this setup, I have shared a working exam ...

A specialized solution designed to avoid loops in references

Is there a method to create a general solution that can prevent circular variables in JavaScript? This solution should be effective for any level of depth or type of circular reference, not limited to the variable itself... So far I've come up with t ...

What is the return type of the Array.prototype.sort() method in Typescript?

I have created a custom type for arrays that are considered "sorted" like this: type Sorted<T> = T[]; This serves as a reminder for developers to provide a sorted array of any type and ensure the sorting themselves. Although I understand that Types ...

Determine the implicit type of the assigned function, while also constraining the return type to be a subtype of a predefined

When writing multiple functions for server requests, I have encountered a dilemma with TypeScript. Each function must return a type that extends a specific predefined known type, but I also want TypeScript to infer the most accurate return type possible. ...

Is there a way to transfer query parameters to my resolver function?

Here is how I initialize the component in my ngOnInit method: ngOnInit() { this.route.queryParams.subscribe( (params) => { console.log(params); } ) } This is my resolver code: class ProductsResolver implements Resolve< ...

Angular issue: "anticipated to exit Angular zone, yet still found within"

I'm currently in the process of building a web application using Angular, and an error keeps appearing in the Chrome console: https://i.stack.imgur.com/sikuu.png Initially, I ignored the error as it didn't seem to impact the app's functiona ...

Disabling click events on a span tag in Angular 6: A step-by-step guide

Is there a way to disable the click event for deleting hours with the 'X' symbol based on a condition? Thank you in advance. <table navigatable class="<some_class>"> <tbody> <tr *ngFor="let item of ...

atom-typescript - What could be causing the unrecognized Typescript configuration options?

I'm puzzled as to why I am encountering the errors depicted in the screenshot below. Atom is indicating that my tsconfig.json file has 'project file contains invalid options' for allowJs, buildOnSave, and compileOnSave. However, according ...

Tips for retrieving a nested data value within an array

I am currently puzzled by the undefined error I encounter when attempting to access a value using dot notation. The following illustrates my point: My goal is to retrieve the value from within the nested object in the headline color array: ...

Angular 8 - Utilizing External URL Routing

After creating a route that generates a token, I encountered an error when trying to retrieve the token from the URL: if (!this.session.token) { let urlToken= 'https://www.url-system.com.br//auth&redirect_uri=http://8000/api/res-token'; let r ...

Dispatch an item containing a list within a list

Currently developing a web application utilizing Angular for user input of two arrays and a matrix, which is then sent to Java for calculations. Utilizing FormGroup for the form fields, the values sent to the server appear as follows: object { targetFuncti ...

Building Reusable Components in Angular 2: A Step-by-Step Guide

I have implemented a feature in my component where a table can be sorted by clicking on the <th></th> tags. When a user clicks on a th tag, the data is sorted either in ascending (ASC) or descending (DESC) order. In my component, I have set up ...

Exploring ways to retrieve Windows environment variables within an Angular 2 JS application

I'm a beginner in Angular2 and I am trying to figure out how to access Windows environment variables in my Angular 2 application. I have an env.js file with the following URLs: (function (window) { window.__env = window.__env || {}; window.__env ...

Using the angular routerLink with query parameters derived from an enumerated key

I have a component that looks like this: export enum QueryParamsEnum { node = 'nodeId' } export class Component { key = QueryParamsEnum.node; } Now, I want to use the key as part of the queryParams in my template like this: <a [rou ...

The Vercel public domain is not functioning as expected

After successfully developing a next.js application with user auth using NextAuth and deploying it to Vercel, I encountered an issue related to the notifications page functionality. The problem arises when the app checks for an active session; if none is f ...

In the absence of localstorage, what alternatives do we have for storing values?

I need a solution to store my value without using local storage, as the value can be visible in the developer tools with local storage. Is there a method to store a value that is hidden from the developer tools? Any guidance would be appreciated. Thank yo ...

The problem arises when the type of a Typescript literal union becomes more specific within React children

Currently, I am in the process of converting our React/Redux project to TypeScript and encountering a challenge with TypeScript literal type union types. The issue that I'm facing is as follows: I have instantiated a Wrapper component with a type pr ...