experimenting with the checked attribute on a radio button with jasmine testing

Currently using Angular 8 with Jasmine testing. I have a simple loop of radio buttons and want to test a function that sets the checked attribute on the (x)th radio button within the loop based on this.startingCarType.

I am encountering false and null test errors and seeking advice on the best way to approach this problem.

Any suggestions would be greatly appreciated.

I've observed that changing [checked]="setChecked(i)" to checked="true" leads to passing tests, which is logical. Therefore, my question/issue revolves around [checked]="setChecked(i)".

HTML

<div class="cars">
  <div *ngFor="let car of arrayOfCarType; let i = index">
    <input
      type="radio"
      name="cars"
      [id]="i"
      [checked]="setChecked(i)"
    />
    <label [for]="i">Car Type {{ i }}</label>
  </div>
</div>

TS

this.arrayOfCarTypes = new Array(4).fill({})
this.startingCarType = 0
....
public setChecked(i: number) {
  return this.startingCarType === i;
}

SPEC

let component: CarComponent;
let fixture: ComponentFixture<CarComponent>;
let input: any;
let startingCarType: number;

beforeEach(async(() => {
  TestBed.configureTestingModule({
    declarations: [CarComponent]
  }).compileComponents();
}));

beforeEach(() => {
  fixture = TestBed.createComponent(CarComponent);
  component = fixture.componentInstance;
  component.arrayOfItems = new Array(4).fill({});
  fixture.detectChanges();
});

describe('setChecked()', () => {
  it('should set checked attribute', () => {

    startingCarType = 0;
    fixture.detectChanges();

    input = fixture.nativeElement.querySelector('.cars div input[id="0"]');

    expect(input.checked).toBeTruthy(); // Expected false to be truthy
    expect(input.getAttribute('checked')).toEqual('true'); // Expected null to equal 'true'
  });
});

Answer №1

SOLUTION: After realizing I was missing a crucial element, I made sure to set the component.startingCarType value.

SPEC

...
it('should confirm checked attribute is set', () => {

  component.startingCarType = 0;
  fixture.detectChanges();

  input = fixture.nativeElement.querySelector('.cars div input[id="0"]');

  expect(input.checked).toBeTruthy(); // this test passes

  });

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

Using a decorator with an abstract method

Discussing a specific class: export abstract class CanDeactivateComponent { abstract canLeavePage(): boolean; abstract onPageLeave(): void; @someDecorator abstract canDeactivateBeforeUnload(): boolean; } An error occurred stating that A decorat ...

Troubleshooting issue with alignment in Material UI using Typescript

<Grid item xs={12} align="center"> is causing an issue for me No overload matches this call. Overload 1 of 2, '(props: { component: ElementType<any>; } & Partial<Record<Breakpoint, boolean | GridSize>> & { ...

What steps can I take to address the problem in iOS 17 where sound is coming from the earpiece instead of the speaker during camera activation?

I have a Progressive Web App where I use the getUserMedia() API to access the camera and HTML audio tags for handling media content. However, ever since updating to iOS 17, I've faced an issue where audio plays through the earpiece instead of the medi ...

Create a constant object interface definition

Is there a way to create an interface for an object defined with the as const syntax? The Events type does not work as intended and causes issues with enforcement. const events = { // how can I define an interface for the events object? test: payload ...

Angular allows for the dynamic updating of og meta tags

Sharing dynamic content on WhatsApp has been made possible through an API. By utilizing the angular Meta class in my component.ts file, I am able to dynamically update the default meta tag property in index.html with the latest content. ...

Instructions for adding a prefix of +6 in the input field when the user clicks on the text box

Recently, I've been utilizing Angular Material elements for input fields which can be found at this link. An interesting feature that I would like to implement is automatically adding '+6' when a user clicks on the phone number field. You ...

Is there a way to upgrade Angular from version 15 to 16 without encountering issues with ESBuild getting blocked and causing the update to fail?

I have been attempting to upgrade Angular from version 15 to version 16. However, when I execute the command ng update @angular/core@16 @angular/cli@16, it initiates the update process but at a certain point, "ESBuild.exe" is triggered and my "ThreatLocker ...

The 'Component' you are trying to use cannot be rendered as a JSX component in Next.js

Take a look at the code in _app.tsx: function MyApp({ Component, pageProps }: AppProps) { return <Component {...pageProps} /> } An error is popping up during the project build process: Type error: 'Component' cannot be used as a JSX comp ...

Exploring a collection of objects in an Angular 2 component

Can someone please assist me in identifying what I am doing wrong or what is missing? I keep getting an undefined value for `this.ack.length`. this._activeChannelService.requestChannelChange(this.selectedchannel.channelName) .subscribe( ...

What is the best way to arrange this script?

I am currently working on a Javascript script that automatically scrolls down and loads a new URL when it reaches the bottom of the page. However, I would like to add a delay of 30 seconds before the new URL is loaded. Although I am relatively new to Java ...

What is the best method to display and conceal a table row in Angular 6?

In the midst of developing a table with multiple rows, I am seeking a way to invisibilize a particular row and then reveal it again using a reset button. Any tips on how to accomplish this task?emphasis added ...

Subscribing with multiple parameters in RxJS

I am facing a dilemma with two observables that I need to combine and use in subscribe, where I want the flexibility to either use both arguments or only one. I have experimented with .ForkJoin, .merge, .concat but haven't been able to achieve the des ...

Angular 5 mobile row aligns vertically, not inline with Bootstrap

Is there a way to make the row inline when the width is less than 579px? I want it to look the same on both mobile and desktop. "styles": [ "../node_modules/font-awesome/scss/font-awesome.scss", "../node_modules/angular-bootstrap-md/scss/bootstra ...

Having trouble transferring data from AppComponent to a function

When I send the email data to this.user in the constructor, it gets stored in AppComponent. Next, I need this variable in the function getUserData to import some data...but the console.log shows undefined, and there is also an error for users: Cannot read ...

Issues encountered when attempting to refresh page with react-router-dom

I successfully implemented a private route system in my React application using react-router-dom. However, I encountered an issue where upon reloading a page, it briefly redirects to /login before properly displaying the page. How can I resolve this unexpe ...

An unexpected error occurred in the file node_modules/@firebase/firestore/dist/index.d.ts at line 27:28 - Please insert a ']' at this location

When adding firebase to my Angular app, I encountered an error while running ng serve: ERROR in node_modules/@firebase/firestore/dist/index.d.ts:27:28 - error TS1005: ']' expected. 27 [K in keyof T & string as `${Prefix}.${K}`]+?: T[K]; ...

When attempting to access the property 'originalname' of an undefined nodejs Mongoose object, an error is triggered

I am attempting to save images using mongoose, express, and multer. However, I keep encountering the following error when testing with Postman: TypeError: Cannot read property 'originalname' of undefined var express=require("express") var ro ...

What is the best way to eliminate the alert message "autoprefixer: Greetings, time traveler. We are now in the era of CSS without prefixes" in Angular 11?

I am currently working with Angular version 11 and I have encountered a warning message that states: Module Warning (from ./node_modules/postcss-loader/dist/cjs.js): Warning "autoprefixer: Greetings, time traveler. We are now in the era of prefix-le ...

Troubleshooting Angular Karma Testing: Uncaught ReferenceError - Stripe not recognized

When running tests with karma, I encountered the following error: ReferenceError: Stripe is not defined Component import { Component, OnInit } from "@angular/core"; import { FormBuilder } from "@angular/forms"; import { Router } from & ...

What could be causing the div to be wider than the content inside of it?

I am having an issue creating a webpage with a 20-60-20 flex fill layout. The div in the center, which should occupy 60% of the page, is wider than its content, causing it to appear off-center. https://i.stack.imgur.com/WwCJy.png Here is my home.componen ...