Issue with Angular 2 Observable testing: Trying to use setInterval in an async zone test is not allowed

I am currently in the process of testing a component that relies on a service for making asynchronous HTTP calls. The service returns an Observable, which is then subscribed to by the component.

Snippet from the service code:

getRecentMachineTemperatures(_machine_Id): Observable<IDeviceReadings[]> {

    return this.http.get(TemperatureService.URL + _machine_Id)
      .map(response => { return response.json(); })
      .map((records: Array<any>) => {
        let result = new Array<IDeviceReadings>();
        if (records) {
          records.forEach((record) => {
            let device = new IDeviceReadings();
            device.device_id = record.device_id;

            if (record.d) {
              record.d.forEach((t) => {
                let temperature = new ITemperature();
                temperature.timestamp = t.timestamp;
                temperature.value = t.temperature;

                device.temperatures.push(temperature);
              });
            }

            result.push(device);
          });
        }
        return result;
      });
  }

Snippet from the component code:

  ngOnInit() {
    this.getRecentTemperatures();
  }

  getRecentTemperatures() {
    this.temperatureService.getRecentMachineTemperatures(this.machine_id)
      .subscribe(
        res => {
          let device1 = res[0];
          this.deviceId = device1.device_id;
          this.initTemperatures(device1.temperatures);
          this.updateChart();
        },
        error => console.log(error));
  }

During my testing process, I set up dependencies and spy on the 'getRecentMachineTemperatures' service method. However, despite multiple attempts at writing tests, each resulted in a different error.

In my test file 'temperature.component.spec.ts', here's my setup:

let machine_id = 1;
let comp:                 TemperatureComponent;
let fixture:              ComponentFixture<TemperatureComponent>;
let de:                   DebugElement;
let el:                   HTMLElement;
let temperatureService:   TemperatureService;
let stubDevices:          IDeviceReadings[];
let stubTemperatures:     ITemperature[];
let spyRecentTemps:       Function;

describe('Component: Temperature', () => {
  // Test setup code goes here
});

The tests using fakeAsync, async, and async (done) are producing various errors including timer queue issues and problems with setInterval within an async zone test.

Any suggestions on how to effectively test components with async service dependencies? Has there been any progress made in fixing these issues or are there workarounds available?

For reference, I am working with angular-cli version 1.0.0-beta.16, node version 4.4.2, npm version 3.10.6, and webpack version 2.1.0-beta.22.

Answer №1

I encountered an issue...

import 'rxjs/add/operator/timeout';

return this.http[method](url, emit, this.options)
    .timeout(Config.http.timeout, new Error('timeout'))

This problem led to an error message. It seems that RXJS .timeout function utilizes setInterval internally.

To resolve this issue, I made a change from...

it('blah', async(() => {     

to

it('blah', (done) => {

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

Show a notification pop-up when a observable encounters an error in an IONIC 3 app connected to an ASP.NET

Currently, I am in the process of developing an IONIC 3 application that consumes Asp.NET web API services. For authentication purposes, I have implemented Token based auth. When a user enters valid credentials, they receive a token which is then stored in ...

showcasing products from database with the help of Angular 12

Here are the files related to the item: Item file And here is the component file: Component file Lastly, this is the data service file: Data Service file However, issues arise when testing the code with console log statements as it indicates that the ...

Discover the highest value within an array of objects, along with any numerical object attributes that have a value greater than zero

Considering an array of objects structured as follows: [{ "202201": { "WO": 900, "WS": 0, "SY": 0.915, "LY": 0.98, "CT": 75 }, "202202" ...

PrimeNG Template not showing the form

I have integrated a form into PrimeNG's turbotable to allow users to create a new entry (group) in the table located within the footer. However, the form is not being displayed as expected. Can you help me troubleshoot this issue? <ng-template pTe ...

Guide on combining vendor CSS files in a React application using Webpack

Incorporating third-party libraries is an essential part of my project. For example, I have Mapbox GL installed via npm, which comes with CSS files needed for its functionality. The Mapbox GL CSS file can be found at mapbox-gl/dist/mapbox-gl.css in the no ...

Tips for syncing the state data stored in local storage across all tabs with Ngxs state management

After converting the state data to base64 format using the Ngxs state management library, I am saving it. While I can retrieve all data across different tabs, any changes made in one tab do not automatically sync with other tabs. A tab refresh is required ...

Observation reveals a lack of return value

I'm encountering an issue with user sign-in functionality. My setup involves using nativescript-angular in conjunction with a Rails 5 API that utilizes devise_token_auth for authentication. The strange thing is that, despite the server logs indicating ...

What is the best method for sharing templates and logic in VUE?

Two separate components with shared logic and template, making it appear as though one is extending the other. Think of Drop and Pick components in this manner: // pick.js import Vue from 'vue' import Component from 'vue-class-component& ...

Angular: Utilizing a nested for loop to dynamically populate a mat-selection-list

The data I'm receiving from my API is structured like this: product name category rating Samsung Galaxy Smart Phone 4 Samsung Galaxy Android 4 Xiaomi Smart Phone 3 This information should be displayed with the product name as the header, ...

Employing an unchanging Map format for observation

I'm currently working on implementing a synchronization mechanism using observable and Map structures from Immutable.js. However, I'm encountering an issue where the Map is unable to function as an observable or perhaps I might be approaching it ...

What is the proper way to conduct unit testing on a function that is invoked in a service's constructor

Is there a way to verify, within the service's spec file, that a function is invoked in the constructor? Consider the following example: @Injectable({ providedIn: 'root' }) export class myService { constructor() { this.myF ...

Could one retrieve the value of a type and save it as a constant?

Can I achieve something similar to this: type YesType = true; const myVar = GetTypeValue<YesType>(); // In this instance, the value true is assigned Is it feasible to assign other fixed values to constant variables like in C++? ...

Having trouble with the "Vs Code nx console generate" command? It seems that there are no flags available to configure

My issue involves the nx console extension installed in my Visual Studio Code. Every time I attempt to use the generate command for components, services, or libraries, I receive an error message stating "ng generate @schematics/angular:component This com ...

Typing should be positioned on either side of the declaration

When I define the type MyType, it looks like this: export type MyType = { ID: string, Name?: string }; Now, I have the option to declare a variable named myVar using three slightly different syntaxes: By placing MyType next to the variable ...

Facing a blank page with no errors displayed during the HTML rendering process in Angular version 6

One of the most frustrating aspects of working with Angular is the lack of information provided when there is a render error in an HTML page. Instead of specifying which page the error is in, Angular defaults to the route page and provides no further detai ...

Having trouble with accessing properties like `d3.svg()`, `d3.scale()` and other features of d3js within an Angular 2 environment

Struggling to incorporate d3.js into angular2. Below is the command I used to install d3 in Angular2: npm install --save d3 install --save-dev @types/d3 This is how my package.json appears: { "name": "my-app", "version": "0.0.0", "license": "M ...

What is the best way to incorporate zone.js into an Angular 2 application?

I have chosen not to use webpack or browserify in my ASP.NET core & Angular2 application. Instead, I am utilizing systemjs to load modules. I am facing a dilemma regarding how to best handle the loading of zone.js within my app. Here are the different opti ...

CORS policy has blocked the Node.JS OvernightJS Express CORS XMLHttpRequest request

I have a back-end API created using Node.js and Typescript that is listening on localhost:3001. Additionally, I have a front-end application built with Angular and Typescript that is listening on localhost:4200. Currently, I am attempting to upload an ima ...

AngularFire 2 dispatching email for password reset

I am looking to add a feature for resetting passwords or handling forgotten passwords using AngularFire2. It looks like the function sendPasswordResetEmail is either not available in AngularFire2 or the typings have not been updated yet. I tried accessing ...

The union type consisting of String, Boolean, and Number in type-graphql has encountered an error

I attempted to create a union type in type-graphql that represents the String, Number, and Boolean classes, but unfortunately, it was not successful. Does anyone have any suggestions on how to achieve this? export const NonObjectType = createUnionType({ ...