Login Component testing encountered an error: Expected false to be true

Having some trouble testing the login feature. Specifically, I want to make sure the submit button is disabled when all input fields are empty. However, the test is throwing an error: "Expected false to be truthy." The strange thing is that this works fine for other scenarios.

Login Component HTML

<form #loginForm="ngForm" (ngSubmit)="onSubmit()">  
    <div class="container">
      <div class="row form-group">
        <label for="email" class="col-md-2">Email:</label>
        <input type="email" class="col-md-4 form-control" id="email" name="email" ngModel required/>
      </div>
      <br />
      <div class="row form-group">
        <label for="password" class="col-md-2">Password:</label>
        <input type="password" class="col-md-4 form-control" id="password" name="password" required ngModel minlength="6"/>
      </div>
      <br />
      <div>
        <button id="submit" class="btn btn-dark" type="submit" [disabled]="!loginForm.valid">
          {{ isLoginMode ? "Login" : "Sign Up" }}
        </button>
      </div>
    </div>
  </form>

================================= Login Component TS

import { Component, OnInit, ViewChild } from '@angular/core';  
import { NgForm } from '@angular/forms';  
import { ActivatedRoute, Router } from '@angular/router';  
import { LoginService } from './login.service';  

@Component({  
  selector: 'app-login',  
  templateUrl: './login.component.html',  
  styleUrls: ['./login.component.css']  
})  
export class LoginComponent implements OnInit {

  isLoginMode = false;  
  alertMessage: string = null;  
  @ViewChild('loginForm', { static: false }) loginForm: NgForm;  

  constructor(private loginService: LoginService, private router: Router, private route: ActivatedRoute) { }  

  ngOnInit(): void {  
  }  
}

===================================== Login Component Spec TS

import { HttpClientTestingModule } from '@angular/common/http/testing';  
import { DebugElement } from '@angular/core';  
import { ComponentFixture, TestBed } from '@angular/core/testing';  
import { FormsModule } from '@angular/forms';  
import { By } from '@angular/platform-browser';  
import { RouterTestingModule } from '@angular/router/testing';  

import { LoginComponent } from './login.component';  
import { LoginService } from './login.service';  

describe('LoginComponent', () => {  
  let component: LoginComponent;  
  let fixture: ComponentFixture<LoginComponent>;  
  let submitEl: DebugElement;  
  let loginService: LoginService;  
  let loginFormEl: DebugElement;  
  let email: HTMLInputElement;  
  let password: HTMLInputElement;  

  beforeEach(async () => {  
    await TestBed.configureTestingModule({  
      declarations: [ LoginComponent ],  
      imports: [FormsModule , HttpClientTestingModule, RouterTestingModule]  
    })  
    .compileComponents();  
  });  

  beforeEach(() => {  
    fixture = TestBed.createComponent(LoginComponent);  
    component = fixture.componentInstance;  
    fixture.detectChanges();  
    loginFormEl = fixture.debugElement.query(By.css("form"));  
    submitEl = fixture.debugElement.query(By.css('button'));  
    email = fixture.nativeElement.querySelector('input[type=email]');  
    password = fixture.nativeElement.querySelector('input[type=password]');  
  });  

  it('should ensure initial input fields are empty', () => {  
    fixture.detectChanges();  
    expect(email.value).toBe('');  
    expect(password.value).toBe('');  
  });  


// Issue Here (Error: Expected false to be truthy.)  
  xit('should verify that submit button is disabled when form is invalid -- Required fields are empty', () => {  
    fixture.detectChanges();  
    fixture.whenStable().then( () => {  
      component.loginForm.form.controls['email'].setValue("");  
      component.loginForm.form.controls['password'].setValue("");  
    })  
   expect(submitEl.nativeElement.disabled).toBeTruthy();  
  });  


it('should validate if submit button is enabled when the form is valid',() => {  
    fixture.detectChanges();  
    fixture.whenStable().then( () => {  
      component.loginForm.form.controls['email'].setValue("<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="354150464175415046411b565a58">[email protected]</a>");  
      component.loginForm.form.controls['password'].setValue("123456789");  
    })  
   expect(submitEl.nativeElement.disabled).toBeFalsy();  
  });  
});

Answer №1

Here are a couple of points to consider:

  1. In my opinion, there is no need to test HTML attributes.

  2. One alternative approach is to try the following method:

// The following test is currently failing (Error: Expected false to be truthy.)  
  xit('should check if the submit button is disabled when the form is invalid -- Required fields are empty', () => {  
    component.loginForm.form.controls['email'].setValue(null);  
    component.loginForm.form.controls['password'].setValue(null);  
    fixture.detectChanges();  
    fixture.whenStable().then( () => {      
      expect(submitEl.nativeElement.disabled).toBeTruthy();  
    })  
  });  

Rather than testing for empty strings, you can experiment with setting null values which may yield better results.

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

Losing scope of "this" when accessing an Angular2 app through the window

My Angular2 app has exposed certain methods to code running outside of ng2. However, the issue arises when calling these methods outside of ng2 as the context of this is different compared to when called inside. Take a look at this link to see what exactl ...

Unable to recreate the Jquery Mobile Autocomplete demonstration

Attempting to recreate a demo using my own remote data source: The HTML page mirrors the demo, with one change: url: "http://localhost/sample.php", Here is the dummy remote data source sample.php <?php $a = array('apple', 'mango&apo ...

Instructions on configuring the chart data in an Angular application sourced from a backend Node.js API connected to a MongoDB database and displayed on an HTML page

app.component.html This particular file is where I showcase my chart <div style="display: block;"> <canvas baseChart width="400" height="400" [datasets]="lineChartData" ...

Is there a way to display the number of active users currently on a page using Pusher?

My goal is to create online classrooms with a maximum of two people in each room, allowing the teacher to know when both the teacher and student are connected. I attempted to track the number of users connected using Pusher's members.me function but ...

Unexpected outcomes can arise from rotating looped meshes

In my current three.js project, I am working with a total of 100 meshes which are organized into 10 different scenes: // Adding 100 meshes to 10 scenes based on an array containing 100 elements for (var i = 0; i < data.length; i++) { mesh = new ...

Unable to retrieve the form from the website

My goal is to extract the login form from: Although I can see the form element when inspecting in Chrome, I'm encountering difficulties retrieving it using the jaunt API in Java. userAgent = new UserAgent(); userAgent.visit("https://etoro.com/login" ...

Refreshing the parent page in Oracle Apex upon closing the child window.When the child window

I have created an interactive report with a form where the interactive report is on page 2 as the parent page and the form page is on page 3 as the child page. In the parent page, I have written JavaScript to open a modal window (form page - page 3) using ...

Creating a typed JavaScript object using an object initializer - step by step guide

When creating an object using direct initialization and showing it in the console, the engine fails to assign it any type. This is not surprising, as the console considers displaying Object to be of little value. However, when a constructor function is use ...

Is there a way to create an input mask that looks similar to this format --:--:--?

Is there a way to format an input in React to accept numbers in the format --:--:-- as 99:99:99 without using any plugins? Unfortunately, I am not sure how to achieve this with a simple input field. However, here is a snippet of code that I tried: <Tex ...

Tips for efficiently utilizing mapActions in vue with Typescript class components!

Can someone please provide guidance on the correct way to use ...mapActions([]) within a Typescript vue class component? This is my current approach: <script lang="ts"> import { Component, Prop, Vue } from "vue-property-decorator"; import { mapActi ...

Refresh the recently added body element in a document - Anglular

Upon logging in with the correct credentials, the server responds with a string containing new elements that include scripts. This element set replaces the content of the login page body. However, after loading the new content, the Angular functions fail t ...

Having trouble retrieving JSON data from a local file using AJAX and jQuery

I am currently facing an issue with passing the content of json.txt in my PHP project folder to JavaScript. It was working fine yesterday, but today it seems that the browser is preventing it somehow... EDIT : Just to clarify, everything is on localhost, ...

Node.js Discord Bot | Config File Manipulation for Improved Functionality

Currently, I am facing a challenge with understanding how my NodeJS bot can effectively read and write data to a config.json file. Additionally, I am unsure about how to identify arguments that are passed along with a Bot Command. With that in mind, I have ...

Modify the date label according to user preference

I am currently working with C#.net to develop a reservation system My goal is to provide the user with the option to change the date using arrows, similar to the image displayed (please click on the link) Date Image https://i.sstatic.net/sBP5r.png I ha ...

Executing a JavaScript function in C#

I am working on a project where I need to store form details and trigger a popup box when the submit button is clicked. To achieve this, I used try { } finally { }. However, I am unsure of how to link the popup box function in JavaScript to the C# file. B ...

The React JSX error message "Maximum update depth exceeded" occurs when there

It appears that I am facing an issue of creating an infinite loop while passing props from one class to another. Despite ensuring that the buttons are correctly bound and trigger only once, the problem persists without any solution in sight after thorough ...

Generate JSON dynamically using a foreach loop

I am utilizing the jquery flot charts library to visualize my data. Take a look at this example JSFiddle I created demonstrating how the JSON structure required for the chart should be. The data I am working with is sourced from a MySql stored procedure a ...

Leveraging Javascript within MVC3, either on a master page or child page

I'm currently developing a web application utilizing MVC3 and I am curious about the best practices for incorporating JavaScript. Specifically, I am uncertain about whether to include JavaScript in the master page as well as in individual child pages. ...

Encountering a 500 error with Ajax in Laravel 5.2

Rediscovering Laravel 5.2 - Starting a Fresh Application After getting back into Laravel, I encountered a challenge with an AJAX post request. Essentially, when you reorder the list, AJAX is triggered to modify the order and save it in the database. Desp ...

Prettier mandates that single-line if-statements without curly braces must be written on the same line

Having recently delved into the EsLint documentation, I've adopted the curly rule set to warning for instances of multiple or nested rows of statements within conditionals. "rules": { "curly":["warn", "multi-or-nes ...