AngularJS and Karma: Revoking ng-dirty status using setPristine

I'm currently facing an issue in one of my unit tests where I am testing the removal of ng-dirty when using setPristine on an input element. Even after calling setPristine, the ng-dirty is not being removed.

My suspicion is that I may be incorrectly implementing the setPristine method.

The specific logic I am attempting to test includes:

  1. Adding text to the input
  2. Testing for ng-dirty and then setting it pristine
  3. Checking for ng-dirty status again

n

/** 
    Add text to your input,
    then test for ng-dirty set the setPristine,
    then check for ng-dirty again. 
*/
it('should set pristine', function() {
    element = angular.element('<input ng-model="temp"></input>');
    element = compile(element)(scope);
    scope.$digest();
    element.val("Some Input");
    element.triggerHandler("change");
    expect(element.hasClass('ng-dirty')).toBe(true);    
    element.triggerHandler('setPristine');
    console.log(element);
    expect(element.hasClass('ng-dirty')).toBe(false);       
});

This code snippet logs:

<input ng-model="temp" class="ng-scope ng-valid ng-dirty">

If anyone can provide guidance on how to resolve this, I would greatly appreciate it.

Thank you in advance

Answer №1

$setPristine is a method that can be accessed through Angular's FormController and ngModelController.

If you have a form named myForm, you can utilize this method as follows:

<form name="myForm"></form>
<div ng-form="myForm"></form>

To set all controls within the form to pristine, simply call myForm.$setPristine().

This concept also applies to individual controls within the form:

<form name="myForm">
    <input name="myInput" ng-model="temp"></input>
</form>

In order to set a specific control to pristine, you can use myForm.myInput.$setPristine().

It is recommended not to rely on testing for the addition or removal of ng-dirty classes, as this delves into the internal workings of $setPristine. To ensure robust testing, focus on verifying that your code correctly invokes $setPristine as intended.

beforeEach(function () {
    element = angular.element(
        '<form name="myForm">' +
        '   <input name="myInput" ng-model="temp"></input>' + 
        '</form>'
    );
    element = compile(element)(scope);

    myForm = scope.myForm;
    spyOn(myForm, '$setPristine');
});

it('should set pristine', function () {
    // Call the relevant code

    // Assert
    expect(myForm.$setPristine).toHaveBeenCalled();
});

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

Experimenting with event monitoring during an ongoing ajax request with the help of Protractor and Angular

My current setup includes protractor 1.7.0 and angular 1.2. I am working on a feature where clicking a button labeled 'Load Results' triggers an ajax request. During this time, another button titled 'Cancel Request' appears to allow us ...

Steps for releasing a third-party library that is compatible with both Angular 2 and Angular 4

Currently, I am utilizing a third-party library for Angular that is compatible with Angular 2. However, I want to make sure this library can support all versions of Angular, including Angular 4 and Angular 5. How can I go about publishing an updated vers ...

Detecting the specific button that was selected with PHP

I am in the process of developing a website for a production company where, upon clicking on a director's name from the menu, all other menu items disappear and only the selected director's biography and work are displayed. My current challenge ...

Using dynamic tag names within React JSX can greatly enhance the flexibility and

I'm working on creating a React component for HTML heading tags (h1, h2, h3, etc.), where the heading level is determined by a prop. Here is how I attempted to approach it: <h{this.props.level}>Hello</h{this.props.level}> My expected out ...

The ng-repeat section is not being updated by the data-binding functionality

I'm brand new to using angularjs and I've encountered a data binding complication. My goal is to display a set of mutually exclusive options, represented by images styled with background-image. When an option is selected, the CSS class 'sel ...

How can we send state updates directly to a conditionally rendered React component?

I am currently developing a React application with a tab section that displays specific components upon clicking on a tab. Initially, I have my parent component: class Interface extends Component { constructor(props) { super(props); ...

Each time a new client connects, socket.io replicates the information

Exploring Node.js and socket.io for the first time, I have developed a small application where a table is meant to be displayed in real-time via socket.io when a function is triggered through a websocket (function triggers an "emit"). However, I'm fac ...

Storing a component in browser storage using JavaScript and Angular

I am currently working on developing an Angular application that allows users to "favorite" a business card and store it in local memory. I am facing challenges with actually storing the clicked element in the browser's local memory. Furthermore, I f ...

Sorting through a table based on the name of the element

I am currently working on filtering an HTML table using a search form. It's working great, but I'm facing an issue where the filtered elements are trying to fill the entire width of the table instead of maintaining their original width (which is ...

Navigating Pre-Fetched Client Routes in Gatsby with @ReachRouter

Let's consider this scenario. Imagine a user enters /company/<company-id> in the address bar. Because the app is completely separate from the backend, it must prefetch the companies. The usual flow is /login -> /company/. Handling this sequ ...

Tips on skipping the need to repeatedly use `@ApiProperty()` for every dto in NestJs-swagger

I'm currently exploring ways to streamline the process of specifying @ApiProperty() for each DTO. I've heard about a method involving the creation of a nest-cli.json file, where if you define Promise<DTO> in your controller within nest-swa ...

Storing a byte array in a local file using JavaScript: A Step-by-Step Guide

Recently, I encountered an issue while working with an openssl certificate. Specifically, when I tried to download the certificate from my API, it returned byte arrays that I needed to convert to a PEM file in order to access them through another API. The ...

tips for choosing tags that are nested within specific parent tags

I'm looking to locate and count all the <"a"> tags within every <"code"> tag on a given webpage using JavaScript. How can I accomplish this? I attempted methods like document.getElementsByTagName("code").getElementsByTagName("a"); and doc ...

Tips for transforming an Observable stream into an Observable Array

My goal is to fetch a list of dogs from a database and return it as an Observable<Dog[]>. However, whenever I attempt to convert the incoming stream to an array by using toArray() or any other method, no data is returned when calling the retrieveDo ...

Moving various divisions through Javascript by clicking various buttons although sharing the same identifier

I am working with the script below: $(document).ready(function() { $('.expandButton').click(function() { $('.expandableSection').toggle("slide"); }); }); My goal is to apply this script to multiple sections. However, ...

Exploring MongoDB's Aggregation Framework: Finding the Mean

Is there a way to use the Aggregation Framework in MongoDB to calculate the average price for a specific Model within a given date range? Model var PriceSchema = new Schema({ price: { type: Number, required: true }, date: { ...

We encountered a ReferenceError stating that 'dc' is not defined, despite having already imported d3, dc, and crossfilter in

In my current angular project, I have included the necessary imports in the component.ts file in the specific order of d3, crossfilter2, dc, and leaflet. Additionally, I have added the cdn for dc-leaflet.js in the index.html file. Despite these steps, wh ...

PHP object representing a datetime in JSON format

How can I convert a JSON datetime object sent to JavaScript into a JavaScript datetime object? The PHP return is: "date": { "lastErrors": { "warning_count":0, "warnings":[], "error_count":0, "errors":[] }, "timezone": { "nam ...

The resource in CosmosDB cannot be found

I have successfully stored documents on Cosmos, but I am encountering an issue when trying to retrieve them using the "read" method. this.cosmos = new CosmosClient({ endpoint: '' key: '' }); this.partitionKey = '/id' thi ...

Explore the world of HTML event listening through .NET integration

Imagine this scenario: within an HTML page, using an UpdatePanel, you have a loading animated gif spinning while ASP.NET processes data from a webservice. I'm curious if there's a way to create an Event in .NET code that can be detected on the H ...