Checking to see if the prop 'isChecked' has been modified

I'm currently facing a challenge with testing whether a class's prop value changes after clicking the switcher.

Below is the component class I am working with:

import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';

@Component({
selector: 'sps-flow-asset-switcher',
templateUrl: './flow-asset-switcher.component.html',
styleUrls: ['./flow-asset-switcher.component.scss'],
})

export class FlowAssetSwitcherComponent implements OnInit {

@Input() isChecked: boolean;
@Output() checkedChange = new EventEmitter<boolean>();

constructor() { }

ngOnInit() {}

onChange(e): void {
    this.isChecked = e.target.checked;
    this.checkedChange.emit(this.isChecked);
  }
}

Here is the template used for this component:

<label class="switcher">
  <input
    type="checkbox"
    [checked]="isChecked"
    (change)="onChange($event)"
   />
  <span class="switcher__slider"></span>
</label>

When it comes to testing, I have started with the following approach:

import { async, ComponentFixture, fakeAsync, TestBed } from '@angular/core/testing';
import { FormsModule } from '@angular/forms';

import { FlowAssetSwitcherComponent } from './flow-asset-switcher.component';

fdescribe('FlowAssetSwitcherComponent', () => {
let component: FlowAssetSwitcherComponent;
let fixture: ComponentFixture<FlowAssetSwitcherComponent>;

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

// Additional test cases are included here...

});

My main goal in testing is to ensure that the prop value changes as expected after certain actions. However, I have encountered an issue when the initial prop value is set to false and needs to be changed to true upon user interaction. This seems to cause the test to fail unexpectedly.

Therefore, my primary question is: What is the best approach to verify if a prop value has been successfully changed after a specific action, such as a click event?

Furthermore, I would appreciate guidance on the correct methods for testing components, especially since this is my first attempt at writing tests.

Answer №1

If you're wondering how to approach this task, I recommend keeping it simple with the following steps:

  • After setting the value of isChecked, make sure to call fixture.detectChanges() to update the input element accordingly.
  • Simply triggering a change event without any actual changes won't be effective. Instead, try clicking on the input element to initiate the desired change.
  • Since there are no asynchronous operations involved, there's no need for async().

To see these suggestions in action, you can check out this sample test on StackBlitz. Here's how your test spec could look like with the proposed changes:

it('should change isChecked from false to true when switcher clicked', () => {
    const inputEl = fixture.debugElement.nativeElement.querySelector('input');
    component.isChecked = false;
    fixture.detectChanges(); // Make sure to invoke detectChanges() after updating 'isChecked'

    // inputEl.dispatchEvent(new Event('change')); // <-- No need for this
    inputEl.click(); // Simply trigger a click event on the inputElement
    expect(component.isChecked)
        .toEqual(true);
});

I also want to thank you for providing all the necessary details in your question! It greatly helped in creating a Stackblitz for testing purposes.

I hope this information proves useful to you.

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

Is there a way to use JavaScript or jQuery to automatically convert HTML/CSS files into PDF documents?

While using OS X, I noticed that in Chrome I have the option to Save as PDF in the print window by setting the destination to "Save as PDF". Is this feature available on Windows? Is there a way to easily save to PDF with just one click? How can I access t ...

Instructions for adding transitions to an entire page in material-ui while maintaining a fixed AppBar

Is there a way to ensure that the material-ui AppBar remains fixed at the top while being wrapped with page contents in a transition? I want the AppBar to transition (e.g. Zoom or Slide) along with the rest of the page contents. I encountered this issue w ...

Creating a search bar with React-Redux: A step-by-step guide

Hey everyone, I've got this component here: const Iphone = ({phones,searchQuery}) => { const filterIphone = phones.map((p, index) => (<div className="model" key={index}> <NavLink to={'/p/' + p.id}>{p.body.mod ...

Exploring the world of ng2-translate for translating texts

For the translation of headings and texts in my Angular2 web application, I utilized ng2-translate. However, I am facing a dilemma when it comes to translating texts that are passed from a .ts file. For example, I can easily translate texts in an HTML fi ...

Discover the Google Chrome Extension that allows you to easily obtain JSON data from your

Here is the structure I have: And below is my manifest.json: { "manifest_version": 2, "name": "Doktor-MD", "description": "Share links on Doktor-MD through the browser.", "version": "1.0", "permissions": [ "http://www.google.com/" ], "browser_action": ...

Mastering the Art of Utilizing Generic Typing to Access Objects

I am trying to find a way to access an object by class using generic typing. The issue I am encountering is that I am getting an error when trying to check if the locators contain an input field. type '{ form1: { item2: { checkbox: string; input: st ...

The Bootstrap validator triggers the form submission only after the second click

When I click on the submit button, I am attempting to submit a form that has its default action prevented and first checks a condition before proceeding. Below is the code snippet: $('#payment-form').bootstrapValidator({ live: 'dis ...

The operation to assign a value to property 'two' cannot be completed as it is currently undefined

I'm facing an issue with the code below and cannot figure out why I am encountering the error message. I have ensured that each object contains a value, so why is there a reference to 'undefined'? Cannot set property 'two' of unde ...

Exploring the power of Typescript and Map in Node.js applications

I am feeling a little perplexed about implementing Map in my nodejs project. In order to utilize Map, I need to change the compile target to ES6. However, doing so results in outputted js files that contain ES6 imports which causes issues with node. Is t ...

Having trouble with the Keydown event - the image isn't moving as expected

Something seems off with my code. I have an image displayed on a canvas, but when I press the specified key, nothing happens. Can you help me figure out where I went wrong? let img = document.getElementById("ship"); let player = { x: 375, ...

Optimal Placement for FB.Event.subscribe

Here is the code I have implemented on my website for the Facebook Like and Share buttons. The functionality works seamlessly. When I click the Like button, a notification is promptly displayed on my Facebook profile page. Additionally, Facebook automatic ...

Rails: Utilizing AJAX to dynamically populate Bootstrap dropdown menus

In the setup I have, there is a dropdown responsible for displaying notifications. <li class="notifications dropdown"> <a class="dropdown-toggle" id="dLabel" role="button" data-remote="true" data-toggle="dropdown" data-target="#" href="/notifi ...

How can I use "Lite-Server" with NPM start to showcase my index.cshtml file on the browser?

Currently, I am trying to navigate the world of Visual Studio Code and figure out how to run/compile my project. Starting a new project in Visual Studio was simple enough, but now that I'm working with Visual Studio Code, I find myself struggling to s ...

Retrieving input values with JQuery

HTML <td data-title="Quantity"> <div class="clearfix quantity r_corners d_inline_middle f_size_medium color_dark m_bottom_10"> <button class="btn-minus bg_tr d_block f_left" data-item-price="8000.0" data-direction= ...

Expiry Time for JWT Token (ASP.NET Core)

I've been trying to extend the lifespan of JWT tokens without success. After researching online, I came across information about JwtBearerOptions.TokenValidationParameters.ClockSkew. I attempted to set timespans of 1 minute and 20 seconds, but the a ...

What is the most efficient way to transfer form data from one JSP page to another?

I need to transfer information from one webpage (1.jsp) to another webpage (2.jsp). The data that needs to be transferred includes checkboxes, radio buttons, and drop downs. This data will be used in 2.jsp to generate the appropriate page. Is there a way ...

After diligently following every step on OneCheckout and getting no response when placing an order, I decided to upgrade my Magento version from 1.6.1.0 to 1.8

After upgrading the Magento version from 1.6.1.0 to 1.8.0, everything seems to be working smoothly. However, customers are facing an issue during checkout where they can't actually place their order. Despite following all the steps correctly, when t ...

tips for concealing a row in the mui data grid

I am working on a data grid using MUI and I have a specific requirement to hide certain rows based on a condition in one of the columns. The issue is that while there are props available for hiding columns, such as hide there doesn't seem to be an eq ...

Employing setTimeout within a repetitive sequence

function displayColors() { $.each(colors, function(index) { setTimeout(function(){ revealColor(colors[index]); }, 1000); }); } I'm attempting to create a loop where the revealColor function is executed every second until all colors ...

Check to see if a key exists within the entire JSON using jQuery

I'm struggling with checking if a specific key is contained in my JSON data array. I want to add a class or perform an action if the key is present, otherwise do something else. I've tried using inArray and hasOwnProperty but can't seem to g ...