Jasmine attempting to access a nonexistent property

I created a very basic component:

import { Component } from '@angular/core';

@Component({
    selector: 'loading',
    templateUrl: './loading.component.html',
    styleUrls: ['./loading.component.scss']
})
export class LoadingComponent {
}

This component simply displays a static loading logo without any user interaction. I decided to write a test to check if it initializes correctly:

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

import { LoadingComponent } from './loading.component';

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

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

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

    it('should exist', () => {
        expect(component).toBeTruthy();
    });
});

When running this test in Firefox, I encountered an error: j is undefined, and in Chromium browsers, the error message was

Cannot read property 'startTime' of undefined
. However, the template used in this component contains only simple text:

Sample Text

There is no reference to 'startTime' in any of these files, so why are these errors occurring?

Note

In other components, I do use properties like startTime, but I cannot understand why that would impact this particular test.

Edit

To resolve this error, I added the following line of code to every test in the project:

afterAll(() => {
    TestBed.resetTestingModule();
});

The error disappeared after implementing this change. I am still unsure about:

  1. The reason behind this solution/the root cause of the issue
  2. Whether adding this line to just one test would have been sufficient

Answer №1

The issue you're encountering is not related to the component and spec file you provided. It seems to be originating from a component that performs an asynchronous operation, and the error occurs after the spec that initiated it has already completed.

Start by adding an 'f' before the describes in this spec file:

fdescribe('LoadingComponent', () => {

This will instruct the spec runner to only execute this particular file, which should pass without any issues.

Next, remove the 'f' and search your project for references to startTime. Run specs for components using this property individually to pinpoint the source of the error.

If you can't identify it, consider adding an 'x' before each describe block one at a time until you isolate the problematic one. The error should disappear when there is an 'x' on the culprit spec.

For specs involving async functions, make sure to use the async function handler to ensure all async tasks are completed before proceeding to the next spec.

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 jQuery autocomplete feature is malfunctioning, as it is unable to display any search

Creating a country list within an ajax call involves working with an array of objects: $.ajax({ url: '//maps.googleapis.com/maps/api/geocode/json?address=' + zipCode + '&region=AT', type: 'GET', dataType: &apo ...

Accessing the .env file to configure a NestJS application using TypeORM and a custom provider

I am still learning my way around nestJS and I am currently trying to configure .env for an existing application but encountering some issues. Within my custom provider for the appModule, it looks like this: @Module({ providers: [ AbcService, ...

Tips for transitioning from Angular to Angular 2: Overcoming key challenges

Our current Angular project is highly developed, but with the emergence of Angular 2 and its advanced features and improved performance, we are considering migrating our existing work. However, we are concerned about the potential challenges that may ari ...

Tips for effectively utilizing the display:none property to conceal elements and permanently eliminate them from the DOM

While working on my website, I utilized CSS media queries to hide certain elements by using display: none. Even though this effectively hides the element from view, it still lingers in the DOM. Is there a way to completely eliminate the element from the ...

Displaying events in the all-day section can be achieved by setting the defaultView of fullCalendar.js to 'agendaDay'

Trying to use fullCalendar.js with defaultView set to agendaDay, and pulling events from mysql as JSON. However, I'm encountering an ERROR where it displays the events in the 'all-Day' section. Here are some of the solutions I attempted: e ...

Can you explain the distinction between using keyof within an indexer versus outside of it?

Consider the TypeScript snippet below: type ForwardVal<T> = { [K in keyof T]: string; }; type ForwardKeyOf<T extends string | number | symbol> = { [K in T]: string; }; type ByObj = ForwardVal<number[]>; // string[] ...

Is it possible to create a channel list using the YouTube API if I am not the owner of the channel? I am not getting any errors, but nothing is showing up

I am currently working on creating a channel list and playlist of videos from a Music channel that I do not own. Here is the link to the channel: https://www.youtube.com/channel/UC-9-kyTW8ZkZNDHQJ6FgpwQ/featured. My goal is to extract data from this channe ...

Is it recommended to use prefixes for name attributes in Angular components?

In my custom angular component, I have radio buttons that look like this. These same buttons are also used in the main component, but they do not function correctly unless the name attributes are changed. Here is the code for the custom component: <di ...

Unable to simulate axios instance in a Typescript environment

After reading through this particular article, I decided to attempt writing a unit test while simulating Axios (with Typescript). Incorporating an Axios instance to define the baseUrl. // src/infrastructure/axios-firebase.ts import axios from 'axios ...

1. "Ensuring the URL of a New Tab Using WDIO"2

During my testing scenario: Navigate to link1 Click a button Open a new tab with link2 How should I verify the link2? I attempted using assert(browser).toHaveUrlContaining(''), but it only verified the link1, causing my test to fail. ...

Ways to refresh the main frame

Here is an example of parent code: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Parent</title> </head> <body> <iframe src="https://dl.dropboxusercontent.com/u/4017788/Labs/child.html" width ...

What causes parseInt to transform a value into infinity?

Here is what I'm working on: let s = '50'; let a = parseInt(s); console.log(a); //outputs 50 console.log(_.isFinite(a)); //outputs false I'm curious why parseInt turns 'a' into infinity when 'a' is set to 50? ...

I'm currently attempting to set up the React JS package, but unfortunately encountering some errors in the process

I'm having trouble installing react as I keep receiving errors. My system has npm version 8.12.1 installed. I attempted to downgrade react, but that didn't resolve the issue. I tried the following steps: Update npm using: npm install npm -g Dow ...

React Table Pagination Bug with Material UI Library

I am currently using Material UI and referencing the table sample provided at https://material-ui.com/demos/tables/. However, when attempting to implement the Custom Table Pagination Action according to the sample, I encountered an error. The error "inher ...

Despite enabling CORS for a specific origin, I am still encountering the error message "No 'Access-Control-Allow-Origin'"

In my front-end application, I am using Angular to request API responses from a web API core project. Despite setting up cross-origin resource sharing for both running on different origins, I am still encountering an error stating 'No Access-Control-A ...

Upon initial loading, the default sidenav in Angular is not selected

I need to ensure that the sidenav loads the basic page during the initial load. This is controlled by the routing.ts file shown below: import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; i ...

Host several Node.js applications concurrently on one server

Attempting to run multiple Node.js apps on a single server has been my focus lately. I have been exploring solutions for similar queries here and have reached some progress. Let's consider the scenario where I have two apps, each serving different HTM ...

Issues with Vuex store causing incorrect value retrieval

In troubleshooting this issue, I am encountering a problem. My request to the back end is to retrieve data for display on the front end. The data fetched from the backend consists of recipes stored in an array. Utilizing v-for, I iterate through the array ...

Customized placement of form fields on an HTML grid determined by the user

My goal is to organize input elements on a grid based on user preferences. After researching, I stumbled upon CSS grids, which seem promising. I am considering creating a CSS grid with r rows and c columns, then using JavaScript to assign input elements t ...

Caution: It is important for each child within a list to have a distinct "key" prop when using react-input

I'm currently facing an issue with the following code snippet: {array.map((item) => ( <> <input key={item.id} type="checkbox" /> ...