Tips for testing the setTimeout function within the ngOnInit using Jasmine

Could someone please assist me with writing a test for an ngOnInit function that includes a setTimeout() call? I am new to jasmine test cases and unsure of the correct approach. Any guidance would be greatly appreciated.

app.component.ts:

ngOnInit(): void {
     if(sessionStorage.getItem("login") === "loggedIN"){
      this.isNav = true;
      this.isUserLogged = false;
      this.loginservice.isLoggedIn = true;
      setTimeout(()=>{
        const isHidden = this.eleRef.nativeElement.querySelector(".header-nav-items");
        isHidden.removeAttribute("hidden");
        this.eleRef.nativeElement.querySelector(".]navigation").classList.remove("theme-black");
        this.eleRef.nativeElement.querySelector(".horizontal-right").classList.remove("profile");
        this.eleRef.nativeElement.querySelector(".horizontal-right").classList.remove("theme-black");
      },500);
     
     }

    }

app.component.spec.ts :

describe('AppComponent', () => {
  let component: AppComponent;
  let fixture: ComponentFixture<AppComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [ RouterTestingModule ],
      schemas: [ CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA ],
      declarations: [ AppComponent ]
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(AppComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create the app', () => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.componentInstance;
    expect(app).toBeTruthy();
  });

I have reached this point in my code implementation.

Answer №1

Take a look at this code snippet

const isHidden = this.eleRef.nativeElement.querySelector(".header-nav-items");
isHidden.removeAttribute("hidden");
this.eleRef.nativeElement.querySelector(".]navigation").classList.remove("theme-black");
this.eleRef.nativeElement.querySelector(".horizontal-right").classList.remove("profile");
this.eleRef.nativeElement.querySelector(".horizontal-right").classList.remove("theme-black");

This code focuses on toggling classes, which can be streamlined using class binding like [class.theme-black]='isLoggedIn'

Within the TypeScript file, you can simplify it to

ngOnInit(): void {
  this.isNav = sessionStorage.getItem("login") === "loggedIN";
  this.isUserLogged = !this.isNav;
  this.loginservice.isLoggedIn = this.isNav;
}

You can enhance the code further like so

ngOnInit(): void {
  this.isNav = sessionStorage.getItem("login") === "loggedIN";
  this.isUserLogged = !this.isNav;
  this.loginservice.isLoggedIn = this.isNav;
}

In your HTML template,

<div class='header-nav-items' *ngIf='!isNav'></div>
<div class='navigation' [class.theme-black]='!isNav'></div>
<div class='horizontal-right'[class.profile]='!isNav' [class.theme-black]='!isNav'></div>

While this may not directly address testing the setTimeout function, it provides a more efficient approach for achieving the desired 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

The Null object within localStorage is identified as a String data type

As someone transitioning from Java development to Javascript, I am seeking clarification on a particular issue. In my project, I am utilizing localStorage to keep track of the user's token in the browser. localStorage.token = 'xxx' When a ...

Retrieving a local variable within an AngularJS controller

Examining the code provided below: app.controller('Controller', function($scope, $http){ $scope.rep = []; $scope.tot = { name: '', marketValue: 0, cash: 0, legend: 'none' }; ...

Nuxt.js is throwing a TypeError because it is unable to access the 'minify' property since it is undefined

When I try to generate a Nuxt app using "npm run generate" or "npm run build", I encounter an issue where it throws a TypeError: Cannot read property 'minify' of undefined. Does anyone know how to solve this? TypeError: Cannot read property &apo ...

The console is displaying the array, but it is not being rendered in HTML format in AngularJS

Can you please review my App.js file and let me know if there are any mistakes? I have provided the necessary files index.html and founditemtemplate.html below. Although it is returning an array of objects in the console, it is not displaying them as inten ...

Struggling with manipulating arrays in Angular 7

Alright, let me give you the gist: Here's the deal - I've got a dataset chilling in sessionStorage, looking something like this: [{ "id": "123:456", "streetAddress": "1020 15th St", "point": { "lati": 35.74633, "longi": ...

Utilizing Regular Expressions in JavaScript to extract packages from an Android manifest document

When it comes to Android APK files, the manifest files play a crucial role: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.myapp" android:versionCode="1" ...

Encountered a network error: A rogue token < was found in JSON at position 0 within a new Apollo

https://i.sstatic.net/D25ai.png const httpLink = createHttpLink({ uri: 'http://localhost:3090/' }) const client = new ApolloClient({ link: httpLink, cache: new InMemoryCache() }) client.query({ query: gql` query users { ...

Tips for determining the full width of a webpage, not solely the width of the window

While we can easily determine the width of the window using $(window).width(); This only gives us the width of the window itself, not accounting for any overflowing content. When I refer to overflowing, I mean elements that extend beyond the visible view ...

Sending POST parameters via Jquery POST from a Java Servlet to Javascript

My JavaScript code initiates a POST request on my Servlet. $.post("RecipeServlet", { r_id: r_id, }, function(data, status){ var foo = data.foo; var bar = data.bar; }); Now, the Servlet is expected to work with the received r_id and then send ...

Ensuring precise accuracy in JavaScript; transforming 0.5 into 0.5000

My current challenge involves converting every fraction number to n decimal places in JavaScript/Node.js. However, I've encountered a roadblock as it appears impossible to convert 0.5 to 0.5000. This discrepancy is causing my test cases that anticipat ...

Implement rotation in Three.js that mirrors the functionality of Blender

Is there a way to permanently change the default rotation of a mesh in three.js after it has been loaded? For example, if I load a mesh with a rotation of 0,0,0, can I then rotate it 90 degrees on the X axis and set this new rotation as 0,0,0? It's i ...

Setting up webRTC and Express.js to function within the same domain requires proper configuration

Currently, I am in the process of creating a video conferencing website using node.js and express.js rather than apache. However, I am faced with some challenges when deciding on the best approach. The main goal is to have the server deliver the website t ...

The completion of RxJS forkJoin is not guaranteed

After subscribing to getAllSubModules, forkJoin executes all the observables without any errors but fails to complete. Even though forkJoin should only complete after all its observables have completed, I'm seeing '-----' printed 3 times in ...

Adjust the transparency of a navigation bar independently from the transparency of the text within the navigation bar

Seeking assistance on adjusting the opacity of this navbar without affecting the text within it. Any tips on changing the text color as well? <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="#" ...

Updating the text area value based on the selected option in a dropdown using Typescript within Angular6

I'm currently facing an issue with updating the text area value based on the selection from a dropdown menu. Below is the design of the dialog: https://i.sstatic.net/67U1M.png Here's the code snippet I've incorporated for this functionalit ...

Using React with TypeScript to ensure that at least one key of a type is not null, even if all keys are optional

Within my Typescript code, I have defined an event type that includes various time parameters: export type EventRecord = { name: string; eta: string | null; assumed_time: string | null; indicated_time: string | null; }; I also have a func ...

jQuery GetJson fails to execute success function

I'm trying to use this code for an Ajax request to a JSON file: let formData = $("#myform").serialize(); $.getJSON("/files/data.json?" + formData, function(response){ alert(response); } ); However, there are no errors and the alert is n ...

Unidirectional data flow from the document object model to the variable within the

When working with Angular, there are multiple methods available for binding variables to DOM properties. You can utilize the `{{}}` syntax, `[property]=expression`, or implement two-way ngModel binding. One aspect that I have not yet discovered is how to ...

Canvas only draws outside the table, with the exception of the first one

I am facing an issue with placing multiple signature pads inside table cells. Only the first canvas gets drawn, while the others remain blank. I have checked the mouse/touch events. The events are triggered (up/down/move) and the draw function is called, ...

Send the template to the enclosed grid column

I enclosed a kendo-grid-column within a new component by using <imx-gridColumn field="Count" title="Count"> ... </imx-gridColumn> The component that includes the imx-gridColumn is templated with <kendo-grid-column #column field="{{field}} ...