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

Assistance with offsetting a jQuery drop down menu

This is the third jQuery script that I've been working on. While parts of it have been inspired by other scripts, I'm now focusing on implementing a specific feature. I've dedicated 4 hours to solving the issue of displaying the submenu on ...

Display HTML content using AJAX within a div element

Within my HTML code, I have the following: <li class="register"><a href="">Registreer</a></li> as well as <div id="content"> </div> I attempted to load an HTML file into the div using the code below in the header se ...

Successfully running npm update on a Mac seemed to have updated the package, however, the

I needed to upgrade my npm version using the following command: npm install npm@latest -g After running the above command, I encountered the following output: /Users/ariful.haque/.npm-global/bin/npm -> /Users/ariful.haque/.npm-global/lib/node_modules ...

Modify the parameters of the apps.facebook.com URL using the Facebook API

Is there a way to modify the parameters in the URL for apps.facebook.com using JavaScript? For instance, if a user chooses a photo, can we change the URL to apps.facebook.com/myapp/?photo_id=23234? This would allow the user to easily share the link with a ...

Access a webpage whose URL has been dynamically assigned using JavaScript

I have a website that consists of a single page and features four tabs. Whenever a tab is clicked, it displays the corresponding content in a div while hiding the other three divs along with their respective content. To ensure a smooth user experience, I u ...

Guide to reference points, current one is constantly nonexistent

As I work on hosting multiple dynamic pages, each with its own function to call at a specific time, I encounter an issue where the current ref is always null. This poses a challenge when trying to access the reference for each page. export default class Qu ...

Transform a base64 image into a blob format for transmission to the backend via a form

Is there a way to convert a base64 string image to a blob image in order to send it to the backend using a form? I've tried some solutions like this one, but they didn't work for me. function b64toBlob(b64Data, contentType='', sliceSiz ...

The script fails to execute on content loaded through AJAX in Django

I have a website with nested div elements that make up a complete set. These elements can be dynamically loaded when the user clicks the "load more" button. The website includes a script that changes the style of the aforementioned div element when the pa ...

Implementing a Vue feature where an object is utilized as the v-model within a select

I am currently working with a select tag that displays an array of objects as its options. Each option only shows the name property of the object. The v-model on the select tag is initially set to one of the object's name properties. My aim is to use ...

When an image is clicked, I am attempting to access data from a Sharepoint list

In my Sharepoint list, there are three columns: Image, Title, and Description. I am using ajax to retrieve the items from the list. The images can be successfully retrieved, but my goal is to display the title and description of the clicked image when an ...

What could be causing the error "Err: user.validPassword is not a function" to occur

I am in the process of developing a node.js app and I have implemented Passport js. After referring to the Passport-local documentation on their official website, I decided to utilize the local passport-strategy. However, I encountered an error stating tha ...

The Socket IO Client is receiving a different object than the one that was sent by the Server

My server side code is sending an object to the client side, but the object received by the client is completely different from what was sent. Let me elaborate: Code Server side code: //Setting up the example var response={}; response.models=[]; respo ...

Is there a way to automatically populate the result input field with the dynamic calculation results from a dynamic calculator in Angular6?

My current challenge involves creating dynamic calculators with customizable fields. For example, I can generate a "Percentage Calculator" with specific input fields or a "Compound Interest" Calculator with different input requirements and formulas. Succes ...

Exploring the Power of Vue 3 in Manipulating the DOM

Hello everyone, I am a beginner with Vue and I am interested in learning how to modify the DOM without relying on methods such as document.querySelector or getElementById. Let's take for instance this input: <input id="myInputId" class=& ...

The command 'npm install -g bigcommerce-stencil/stencil-cli' failed to run properly in the Windows command prompt

Having successfully completed all installations on my Windows 7 SP1 PC, I attempted to run the following command: npm install -g bigcommerce-stencil/stencil-cli Unfortunately, I encountered an error as shown in the screenshot below: error screen For mo ...

Transfer information from PHP to JavaScript across distinct files

In my website, I have several files including login.php, main.php, functions_js.js and functions_php.php. The login.php file retrieves two variables that I need to pass to the functions_php.php file via AJAX. In functions_php.php, I execute a SELECT query ...

Tips for adjusting the div style when resizing the browser

As I work on a script, I encounter an issue where the style of a div should change when it becomes larger due to resizing. Even though I have come up with a solution for this problem, there are still some inconsistencies. Sometimes the width is reported a ...

having difficulty grasping the variable's scope within this code

Here we have a code snippet where the variable vid is initialized inside a function. The question arises on how this variable can be used outside the function, specifically in the context of vid.play(). How does the program know that vid was created usin ...

Setting an if isset statement below can be achieved by checking if the variable

I have included a javascript function below that is designed to display specific messages once a file finishes uploading: function stopImageUpload(success){ var imagename = <?php echo json_encode($imagename); ?>; var result = '& ...

I do not prefer output as my optimal choice

My preference is to create drill down buttons rather than focusing on output. Currently, the output appears as: The content of index.html is as follows: <html>  <head> <script type="text/javascript" src="http://ajax.googleapis.com/ ...