Karma Jasmin is puzzled as to why her tests are failing intermittently, despite the absence of any actual test cases

In this snippet, you will find my oninit method which I am instructed not to modify.

  ngOnInit(): void {
        this.setCustomizedValues();
        this.sub = PubSub.subscribe('highlightEntity', (subId, entityIdentifier: string) => {
          document.querySelector(entityIdentifier).classList.add('highlight');
    
          setTimeout(() => {
            document.querySelector(entityIdentifier).classList.remove('highlight');
          }, 2000);
    
        });
      }

Below is a basic test setup for reference

describe('aComponent', () => {

    
  let httpCallerServiceStub = jasmine.createSpyObj('httpCallerServiceStub', ['get']);

  let fixture: ComponentFixture<aComponent>;
  let componentInstance: aComponent;
  localStorage.clear();
  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [aComponent],
      providers: [
        {
          provide: HttpCallerService,
          useValue: httpCallerServiceStub
        }],
      imports: [CommonModule, CmcSpinnerModule, NgbModule],
    }).compileComponents();

    fixture = TestBed.createComponent(aComponent);
    componentInstance = fixture.componentRef.instance;
    fixture.autoDetectChanges();
  });

 describe('ngOnInit method', () => {
    beforeEach(() => {
      fixture.componentInstance.customized = {};
    });

    it('should initialize with minimum input', () => {
      // Triggers ngOnInit
      fixture.detectChanges();
      expect(fixture.componentInstance.customized).toEqual({});
    });
  });

The issue arises where tests fail inconsistently due to 'classList' of null error

"message": "An error was thrown in afterAll\nTypeError: Cannot read property 'classList' of null\n    at <Jasmine>\n 
   at webpack:///components/path/aComponent.ts:35:53

This error on line no. 35 in the oninit function, points to the following lines:

   setTimeout(() => {
                document.querySelector(entityIdentifier).classList.remove('highlight');
              }, 2000);

I have a few questions regarding this situation:

  1. Even after trying tick(2000) and fake async in a simple ngonit test, the random errors persist. How can I resolve this? (referred from this answer)

  2. Is there something missing in my testbed configuration? Because even when I exclude the oninit test and check another function without fixture.detectChanges(), the same random error occurs.

  3. Running tests using fdescibe results in passing all tests every time. The issue only emerges when I remove the 'f' from fdescribe and run all tests including other components as well.

Any guidance on resolving this dilemma would be greatly appreciated, as I have been stuck on this for the past 4 days.

Answer №1

Continuing the conversation from the comments:

Instead of trying to make aComponent work in other unit tests, I recommend using mocks. This way, you avoid running into errors every time you add new dependencies or initialization code. If you don't intend to test that functionality within its parent component, a mock should suffice.

You can also eliminate any ticks and such...

@Component({
  selector: 'a-component', //ensure the selector matches the real component
  template: '<p>Mock A Component</p>'
})
class MockAComponent {}

beforeEach(() => {
  TestBed.configureTestingModule({
      declarations: [
        ParentComponent,
        MockAComponent ,
      ],
      // ...
  });
});

Alternatively, you can simply install and use ng-mocks, eliminating the need to create mocks separately.

beforeEach(() => {
  TestBed.configureTestingModule({
      declarations: [
        ParentComponent,
        MockComponent(AComponent),
      ],
      // ...
  });
});

Learn more about this topic from: Mocking Child Components - Angular 2

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

My component reference seems to have gone missing in angular2

Trying to load my Angular 2 app, I encountered this error: https://i.stack.imgur.com/FmgZE.png Despite having all the necessary files in place. https://i.stack.imgur.com/kj9cP.png Any suggestions on how to resolve this issue? Here is a snippet from ap ...

Developing Angular2 applications in Visual Studio Team Services (formerly known as Visual Studio Online)

Currently, I have an angular2 client integrated into a Visual Studio vNext (ASP.Net 5) project. During my attempt to create a build in Visual Studio Team Services, I encountered errors similar to this one during the build step: It appears that module &a ...

Angular is showing an error indicating that the property "name" is not found on an empty object

After thorough checking, I have confirmed that the property does exist with the correct key. However, it is returning an error message stating name is not a property of {}. I attempted to assign this object to an interface along with its properties but enc ...

Tips for saving an Angular project for offline use

I have created a basic form for a family member to use in their medical practice, and I want to make it functional offline. The form simply captures data and displays it, with no need to send or store the information anywhere. What would be the most effect ...

What causes content to overflow a flex container?

Hey there, I currently have the following structure: <div fxLayout="row" fxLayout.xs="column" fxLayoutAlign="space-around start" fxLayoutGap="2%" style="padding:2%;"> <div fxFlex style="line-height:2;"> <md-card> ...

"Exploring the dynamic duo: Algolia integration with Angular

I've been following a tutorial on implementing instantsearchjs in my website, which can be found here. Everything is set up correctly and I can query for results in .JSON format from my website. However, I'm having trouble figuring out how to r ...

Understanding authorization and user roles within an Angular 2 application utilizing Microsoft Graph

As a newcomer, I am in the process of developing a CVThèque application using angular 2 and .net core. For authentication purposes, I have integrated Microsoft Graph and adal successfully. However, I am unsure how to set up permissions and group roles for ...

I will evaluate two arrays of objects based on two distinct keys and then create a nested object that includes both parent and child elements

I'm currently facing an issue with comparing 2 arrays of objects and I couldn't find a suitable method in the lodash documentation. The challenge lies in comparing objects using different keys. private parentArray: {}[] = [ { Id: 1, Name: &ap ...

What is the process for integrating mobiscroll into an Angular project using a customized username?

After installing the mobiscroll trial in my angular project, I decided to reinstall it with a new username. Despite attempting to remove the library and using the command "mobiscroll config angular", I encountered an issue where it was still logging in w ...

What is the best way to implement callbacks with $http in Typescript?

When making my $http call, I am looking for the most adaptable way to handle all the parameters returned in the .success and .error functions. Here is an example of what my $http call looks like: this.$http({ url: "/api/x", method: "GET" }) .success((? ...

Managing optgroup in select dropdown using Angular 4

Is there a way to retrieve the optgroup label value within an onchange function on a select box in Angular 4? In my form, I have a select box with multiple dates as option groups and time slots in 24-hour format for booking (e.g. 1000 for 10AM, 1200 for 1 ...

Angular ngFor not displaying the list

I'm encountering an issue with my HTML page where I'm using NGFor with an array. The error message I receive is as follows: landingpage.component.html:142 ERROR Error: Cannot find a differ supporting object '[object Object]' of type &ap ...

Struggling to utilize a custom react-three-fiber component despite specifying the custom type within the react-three-fiber module

Currently developing a react application focused on visualizing mathematical concepts with the help of react-three-fiber. Utilizing TypeScript, I discovered that by extending custom ThreeElements (https://docs.pmnd.rs/react-three-fiber/tutorials/typescript ...

Establishing a typescript class as an interface

While attempting to upgrade to TypeScript 3.5, I ran into an issue with a signature that has been overlooked by the ts-compiler, despite being present for years. A third-party framework (knockoutJS) requires me to pass something that adheres to this: int ...

How can I invoke the header component function in another component using Angular 2?

Is there a way to invoke the showmodel(displayType) function from another component? How can I call a function in the header component from a different component? header.component.ts import { Component,Renderer } from '@angular/core'; i ...

Cannot establish a connection with Socket.IO

I've encountered an issue with establishing a connection to Socket.IO in my node server. Although the server starts successfully with Socket.IO, I am not seeing any console logs when trying to connect to Socket. this.server.listen(this.port, () => ...

Heroku is having trouble deploying an app that has both frontend and backend components merged together

I am currently facing an issue with my Angular frontend and Node.js backend app when deploying it to Heroku. The build and compile process is successful, but it seems that only the backend is running on Heroku when attempting to access the app. I have foll ...

Clicking on hyperlink within email to open in default web browser

I am facing a problem with my Angular web app. Here is the scenario of the issue: When I send a link to my app via email and try to open it from a mobile email client using a short version of a browser or webview (not sure what it's called), I encou ...

Guide to sending a HTTP POST request with parameters in typescript

I need assistance sending a POST request using parameters in the following format: http://127.0.0.1:9000/api?command={"command":"value","params":{"key":"value","key":"value","key":"value","key":value,}} I attempted to do this but encountered an issue: l ...

Discovering the power of Angular: Leveraging nativeElement to enhance your click handlers

Perhaps just a "stylish" yet effective solution... Here's what I have that is functional: // Template <div *ngFor="let media of period.media"> . . . <button #btn (click)="onDeleteClick(btn)" [attr.media-id]="media.ID"> ...