Having trouble getting the embedded setInterval function to work properly within an observable in a test scenario

I've created a controller class for a countdown timer that is functioning correctly on the webpage, but I'm encountering issues with running my unit test. I am unsure if the problem lies in how I am executing the test or if there is an issue within the class itself.

Below is the code for the class being tested:

import { Observable, Subscription } from 'rxjs'

    export class CountDownTimerController {
         public secondsTimer$ : Observable<any>;
         private counter : number;
         private _counterActive: boolean;
        
         public get counterActive(): boolean {
            return this._counterActive;
        }
         
        constructor() {
            this.counter = -1;
            this._counterActive = false;    
            this.startTicker();
         }
    
         start() {
            this._counterActive = true;
            console.clear();
            console.log(`Started, _counterActive is ${this._counterActive}`)
         }
         pause() {
            this._counterActive = false;
         }
         reset() {
             this.pause()  
             this.counter = 0;
         }
         public get count() : number {
            return this.counter
         }
         private startTicker() { 
             if (this.secondsTimer$) {return}
             let self = this;
   
            this.secondsTimer$ = new Observable(observer => {
                let interval = setInterval(() => {
                    console.log(`Time: ${Date.now()} interval triggered.  counterActive ${self._counterActive} counter: ${self.counter}`)
                    if (self._counterActive) {
                        self.counter = self.counter + 1;
                        observer.next(self.counter)
                    }
                }, 1000);
                return function unsubscribe() {clearInterval(interval);
                }
            })
         }
    }

The following is the test I am executing:

fit('Starts counting seconds when the start method is called', async ()=>{
        console.log("Starting test")
        let controller = new CountDownTimerController();
        expect(controller.count).toBe(-1,"Should be initialized to -1");
        expect(controller.counterActive).toBeFalse;
        controller.start(); 
        expect(controller.counterActive).toBeTrue
        console.log(`Time: ${Date.now()} Controller started`)
        await utils.sleep(2000);  //WAIT FOR TWO TICKS OF SetInterval
        expect(controller.counterActive).toBeTrue();
        console.log(`Time: ${Date.now()} Waited 2 seconds`)
        console.log(`Counter: ${controller.count}`)
 --->   expect(controller.count).toBeGreaterThanOrEqual(1,`Ticker should be 1 or more at time ${Date.now()}` )
        //ISSUES WITH THE ABOVE LINE
       console.log("Test completed")
    });

If you are interested, below is the implementation for utils.sleep:

 export const sleep = (ms: number) => {
    return new Promise(resolve => setTimeout(resolve, ms))
}
 

Here is the output in the console:

Started, _counterActive is true count-down-timer-controller.spec.ts:37 
Time: 1625597279827 controller started count-down-timer-controller.spec.ts:40 
Time: 1625597281829 Waited 2 seconds count-down-timer-controller.spec.ts:41 
Counter: -1 count-down-timer-controller.spec.ts:44 
Test completed
debug.js:15 FAILED CountDownTimerController starts counting seconds when start is called
debug.js:21 Error: Expected -1 to be greater than or equal 2, 'Ticker should be 1 or more at time 1625597281829'.
    at <Jasmine>
    at count-down-timer-controller.spec.ts:42
    at <Jasmine>
    at fulfilled (tslib.es6.js:71)
debug.js:6 Skipped 27 tests

Answer №1

Since you didn't subscribe to the observable (this.secondsTimer$), the interval was never initiated or triggered.

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

Dealing with type errors involving null values when using interfaces in Typescript

I encountered an issue related to the error property within the defaultState constant: interface AuthState<T = any> { auth: T; error: null | Error; loading: boolean; } export const defaultState: { auth: null | AuthState } = { auth: null, e ...

Display the customer's name using the Mat-Select display object property by fetching it from the previously selected or saved value

Having some difficulties with mat-select and options in my Angular 6 project. Here is the scenario I am facing: I would like to create a dropdown list of organizations where I can select one and save the complete organization object, not just its name. ...

Error in VS Code related to Vue Array Prop JSDoc TypeScript: The properties of type 'ArrayConstructor' are not found in type 'MyCustomType[]'

After reading the article "Why I no longer use TypeScript with React and why you might want to switch too", I decided to work on a Vue CLI project using ES6 without TypeScript. Instead, I enabled type checking in Visual Studio Code by utilizing JSDoc / @ty ...

The submit button is getting disrupted by the background image being set

Implement the following CSS code to set a background image on a single-page app (Angular). .page::before { content: ''; position: absolute; background-size: cover; width: 100%; height: 100%; background-image: url("../../assets/weird. ...

Angular: ViewContainer is failing to correctly insert the component next to the anchor element, instead it is placing the component inside the anchor element

I have successfully implemented a tab view with the following structure: <tabs> <ul #getVCRefHERE > <li>tab1</li> <li>tab2</li> </ul> <tab> <ng ...

What is the best approach for incorporating a customized set of valid keywords into a text input field in JHipster while maintaining a sophisticated design?

My code snippet is not displaying the input even though all the necessary elements are in place: home.component.ts <p class="lead">Input: </p> <div><jhi-calculator-input></jhi-calculator-input></div> calculator.compon ...

Vercel encountered issues with "validating code quality and type correctness" during deployment but was successful when performed locally

Running "next build" locally and "vercel build" both work smoothly. However, once deployed to vercel, the "Linting and checking validity of types" fails during the build process. It seems like TypeScript is stricter when building on vercel even with the sa ...

How to refresh a page manually in Angular 2

How can I have a page in Angular reload only once when a user visits it? This is my attempt: In the homepage component, I added the following code: export class HomepageComponent implements OnInit { constructor() { } ngOnInit() { location.relo ...

Switching to Angular's routing, prioritize removal of the previous component

I'm currently using [routerLink]="['my-route']" in my Angular project. However, I've encountered an issue with the routing system where it renders the new component first and then removes the old one from the DOM. This is caus ...

In Chrome, Angular http request returns null while in Firefox, it functions as expected

Recently, I encountered a strange issue while working on my Angular 7 project. For the past two months, everything was running smoothly without any problems. However, all of a sudden, I started getting null returned for all my HTTP requests in Chrome. Surp ...

Local font not applying styles in Tailwind CSS

I integrated the Gilroy font into my application, but I am facing issues with tailwindcss not being able to style the text properly. The font appears too thin in all elements such as paragraphs and headers. Here is the file structure for reference: https: ...

Enhance video performance by utilizing multiple sources

We are facing a unique challenge on our homepage (built with Angular and Server Side Rendering): Directly under the header, we have a video element that spans full width and height (100vh) with autoplay and muted settings. This video has two different sou ...

Learn how to dynamically activate an icon in Angular to enhance user interaction

HTML Code: The Zoom Component <div class="zoom py-3"> <i nz-icon nzType="minus" (click)="zoomToggle(false)" nzTheme="outline"></i><br> <i nz-icon nzType="plus" (click)=&q ...

Pagination feature in MUI DataGrid table is malfunctioning

I'm struggling to get the pagination feature to work in my Material UI DataGrid component, but I'm hitting a roadblock: https://i.stack.imgur.com/eT7s7.gif The console is not showing any errors. Here is the code for my component: import { ...

Structural directive fails to trigger event emission to parent component

Following up on the question posed here: Emit event from Directive to Parent element: Angular2 It appears that when a structural directive emits an event, the parent component does not receive it. @Directive({ selector: '[appWidget]' }) export ...

Are there more efficient alternatives to utilizing arrays and index-based functions for storing in-memory data in TypeScript?

Is there a more efficient method for storing and retrieving data besides relying on Array index-based calls? For instance: export interface EntityInterface { id: number; name: string; age: number; } export class ClassName { entities: Enti ...

Steps for assigning the TAB key functionality within a text area

Is there a way to capture the TAB key press within a text area, allowing for indentation of text when the user uses it? ...

Issues preventing Angular2 project from being operational

My angular 2 project was running smoothly on my ubuntu machine until I encountered this error. Strangely, just 5 minutes ago it was working fine. The issue arose after I ran another ionic2 project and now the angular project is throwing the following err ...

Calculate the total by subtracting values, then store and send the data in

Help needed with adding negative numbers in an array. When trying to add or subtract, no value is displayed. The problem seems to arise when using array methods. I am new to arrays, could someone please point out where my code is incorrect? Here is my demo ...

The error being thrown at line 538 in the module.js file is causing issues when using

I encountered an error in my Angular 4 project that says "module.js:538 throw err;". Can anyone provide insight on what this means? module.js:538 throw err; ^ Error: Cannot find module 'swagger-js-codegen' at Function.Module._resolveFilena ...