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

Why does the "revalidate" field in Incremental Static Regeneration keep refreshing without considering the specified delay?

I am currently referencing the guidance provided at: https://nextjs.org/docs/basic-features/data-fetching/incremental-static-regeneration. My intention when setting the revalidate: 60 * 10 parameter is: To have the content remain consistent for at least ...

Exploring the Issue with SWR Hook in Next.js using TypeScript

Seeking assistance with the SWR hook as I navigate through some challenges while attempting to use it effectively. This time, the issue appears to be minor. The objective is to set a breakpoint in my API to retrieve data, using axios. The problem arises ...

Typescript filtering function that results in an empty array

Struggling with filtering an array in typescript and aurelia as I keep getting empty lists. For example, when searching for the keyword ra within the firstName property, I expect to retrieve the object with the name "Raja". Not sure where I'm going w ...

Customizing the appearance of Indicators and Paginator in PrimeNG Carousel

I have integrated a carousel using PrimeNG which has the following design here Take note of the style of the carousel indicators and navigators. I want to achieve the default style of indicators/navigators for the carousel as shown here I have included t ...

When trying to create a new project using `ng new project`, the path specified was not

I'm attempting to start an angular 4 project using angular-cli on my Windows 10 operating system. I followed the instructions outlined at https://www.npmjs.com/package/@angular/cli. Currently, I am running node - 7.6.0 and npm - 5.1.0. Every time I ...

What is the best way to specify the return type of a currying function?

Check out this currying function I've implemented: export interface NewIdeaCardSubmit { title: string, description: string, categories: CategoryValues } const applyInputs = (title: string) => (description: string) = ...

Using Angular2 translate in expressions: a step-by-step guide

Looking at the code below, you'll notice that starting from line 44, the titles are already enclosed within {{}} expressions: import { Component, ViewChild } from '@angular/core'; import { Events, MenuController, Nav, Platform } from ' ...

What is the process for setting a push key while pushing data to a Firebase database?

When writing data to the Firebase database using both Angular 4 on the frontend and Firebase functions on the backend, a unique push key is generated by Firebase. This key makes it difficult to access the data in the future. I am curious if there is a way ...

Typescript error: The property 'set' is not found on type '{}'

Below is the code snippet from my store.tsx file: let store = {}; const globalStore = {}; globalStore.set = (key: string, value: string) => { store = { ...store, [key]: value }; } globalStore.get = (key) => { return store[key]; } export d ...

What is the best way to display the values from an array in a child component and pass them to the

How can I retrieve values from an array in the child component and display that data in the parent component? Initially, I was only displaying data from the array when the 'save' button was clicked. Now, I need to display the array by default. ...

Having trouble receiving a blob response using HttpClient POST request in Angular 9?

I'm encountering an issue while attempting to receive a zip file as a blob from an HTTP POST request. However, the resolved post method overload is not what I expected. const options = { responseType: 'blob' as const }; Observable<Blob ...

Discover the combined type of values from a const enum in Typescript

Within my project, some forms are specified by the backend as a JSON object and then processed in a module of the application. The field type is determined by a specific attribute (fieldType) included for each field; all other options vary based on this ty ...

The state of the checked value remains unaffected when using the Angular Material Checkbox

I am currently working on a list of elements and implementing a filter using pipes. The filter allows for multi-selection, so users can filter the list by more than one value at a time. To ensure that the filter persists even when the window is closed or t ...

The module for the class could not be identified during the ng build process when using the --

Encountering an error when running: ng build --prod However, ng build works without any issues. Despite searching for solutions on Stack Overflow, none of them resolved the problem. Error: ng build --prod Cannot determine the module for class X! ...

Leverage the capabilities of one service within another service

I have been working on enhancing the functionality of Http so that when a user encounters a 403 error, their user information is removed and they are redirected to the login page. I have shared an example of AuthHttp below for reference. @Injectable() ...

One way to change the cursor CSS property is by dynamically altering it based on scrolling behavior. This involves modifying the cursor property when scrolling

I'm attempting to adjust the cursor property within an Angular function. The issue I'm facing is that when I begin scrolling the webpage, the cursor changes to a pointer, but when I stop scrolling, it remains as a pointer. I've attempted to ...

Dealing with Errors in Angular 8: Best Practices for Handling Response Errors

When an error is thrown from the WEB API, I do not receive any response and the debugger does not hit. However, in case of success, I do get a response and the debugger hits. All I want is to receive an error response and have the debugger hit every time, ...

Using ionic-v4 to browse through a application via its URL pathways

I am facing an issue with navigating to specific pages on my website using the URL. For example, I want to access page 1 by typing in the address bar: localhost:8100/mySite/page1 and go directly to page 1 localhost:8100/mySite/page3 and navigate to pag ...

Tips for creating objects with optional properties

I need help figuring out the best way to handle situations where a variable can either be defined or empty. Currently, I'm using Partial, but it doesn't provide the accurate outcome. The specific scenario involves MobX observables that begin as ...

Error: Request Timed Out - The asynchronous callback function was not executed within the specified timeout set by the jasmine.DEFAULT_TIMEOUT

Currently, I am in the process of testing my Ionic app using Jasmine. Below is a snippet from my test suite: beforeEach(() => { auth = new Authentication(<any>new HttpMock(), <any>new StorageMock()) user = new MockUser(); head ...