Unit test: Using subjects instead of observables to mock a service and test the change of values over time results in TypeScript throwing error TS2339

I have a unique scenario where I have implemented a service that accesses ngrx selectors and a component that utilizes this service by injecting it and adjusting properties based on the values retrieved.

For unit testing purposes, I am creating mock versions of the service to return various values for different tests. To achieve this, I have modified the mock service to use subjects instead of observables. Although the tests are successful, TypeScript raises an error indicating that the interface of the mock service does not align with the actual service since the latter uses observables.

Check out the Stackblitz here

The Stackblitz demonstration functions correctly, but TS shows the error: TS2339: Property 'next' does not exist on type 'Observable'

I discovered that I could address this issue by adding // @ts-ignore above each .next() call to instruct TypeScript to overlook the error. However, I believe there might be a more efficient solution available.

Is there a better method to mock the service so it retains observables while offering the flexibility to provide distinct values for individual unit tests?

Answer №1

One way to ensure that the real service and the mock return the same thing is by utilizing the .asObservable() method on the BehaviorSubject. Additionally, you can use the do() method to set a new value into the BehaviorSubject.

To illustrate this concept, I have created a StackBlitz. Below is an example of the MockTestService from that StackBlitz:

MockTestService {
    private _test$ = new BehaviorSubject(10);
    public test$ = this._test$.asObservable();
    do(param: number): void { this._test$.next(param); }
}  

I trust this explanation proves useful to you.

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

Guide on formatting the API response using a callback function in Angular development

How can I reformat my API response using a callback function and access the data within the angular subscribe method? I attempted to use mergemap but it didn't work as expected. this.http.get('https://some.com/questions.xml', {headers, res ...

Experimenting with an rxjs service to perform a GET request within the component

When calling the service function, the syntax is as follows: get getLayerToEdit(): BehaviorSubject<VectorLayer> { return this.layerToEdit; } This function is then invoked in the ngOnInit method like this: ngOnInit() { this.annoServic ...

Utilizing Spring Boot, Message Queues, Node.js, and Angular to build a scalable microservices

Hello everyone! I recently received a challenging exercise that has left me feeling a bit lost. I was hoping someone could offer me some guidance to get started in the right direction! :) You can find the description of the exercise here (unable to embed ...

An error occurred due to an unexpected token found in the JsonForms custom-renderer props

I found inspiration in an example from this website to develop a custom renderer for JsonForms using Vue: However, as I implement this example in my .vue file within the script tags, I encounter an error UnexpectedToken right after declaring the props. It ...

What is the appropriate method to utilize the scrollable feature in Tab View?

Currently, I am incorporating p-tabview and trying to enable the scrollable property as indicated on the primeng website: https://www.primefaces.org/primeng/showcase/#/tabview However, an error is showing up that says Can't bind to 'scrollable&a ...

Tips for creating animations using parent and child components in Angular

Despite my best efforts, it seems like this should be functioning properly... but unfortunately it's not... I'm attempting to achieve a transition effect on the parent element (ui-switch-groove) while the child element (ui-switch-dongle) moves. ...

Unable to create resource in nestjs due to typeScript compatibility issue

Encountered an Error: TypeError: Cannot access 'properties' property of undefined Failed to execute command: node @nestjs/schematics:resource --name=post --no-dry-run --language="ts" --sourceRoot="src" --spec Attempts made ...

Learning how to implement GraphQL in Angular without relying on the Apollo client library poses an exciting challenge for

Exploring ways to incorporate GraphQL into my Angular app without relying on the Apollo client. Any suggestions on how this can be achieved? Although I've used the Apollo client for connecting to a GraphQL API in the past, I'm curious about alte ...

Tips for creating Junit tests for a CDK environment

As a newcomer to CDK, I have the requirement to set up SQS infrastructure during deployment. The following code snippet is working fine in the environment: export class TestStage extends cdk.Stage { constructor(scope: cdk.Construct, id: string, props: ...

Incorporate typings into your CDN integration

I'm interested in utilizing a CDN to access a JSON validation library, as it's expected to provide faster performance (due to retrieving the file from the nearest server within the CDN). The JSON validation library in question can be found here: ...

Is it possible to utilize the System.import or import() function for any JavaScript file, or is it restricted to single module-specific files?

After reading an intriguing article about the concept of dynamic component loading: I am interested in learning more about the use of System.import. The author demonstrates a specific syntax for loading the JavaScript file of the module that needs to be d ...

What is the best way to automatically close a parent popup window when the child popup is

Currently, I am developing a web application using Angular that requires managing nested popups. Specifically, in my scenario, I initiate Popup 1 and from within that popup, I trigger another popup (Popup 2) upon clicking "delete." My goal is to ensure tha ...

Toggle the visibility of an input field based on a checkbox's onchange event

I am facing a challenge where I need to display or hide an Input/Text field based on the state of a Checkbox. When the Checkbox is checked, I want to show the TextField, and when it is unchecked, I want to hide it. Below is the code snippet for this compon ...

Modify the ngb-timepicker formatting to output a string instead of an object

I am currently working on modifying ngb-timepicker so that it returns a string instead of an object. Right now, it is returning the following format: { "hour": 13, "minute": 30 } However, I want it to return in this format: "13:30" This is the HTM ...

A technique for deactivating reactive forms control within a nested formArray

Is there a way to selectively disable individual controls within the 'fields' group which is nested under this.form.get('groups').controls? I know how to disable an entire group by using this.form.get('groups').controls.disabl ...

The object in an Angular 11 REACTIVE FORM may be null

I am looking to incorporate a reactive form validation system in my application, and I want to display error messages based on the specific error. However, I am encountering an error that says: object is possibly 'null'. signup.component.html &l ...

Update a component using a different component

Hello there, I am currently working with Angular 7 and wanted to share the component's structure: https://i.sstatic.net/EvmOi.png At the moment, I am passing data from Comp_3 to Comp_2 in order to update the 'Message' field. However, this ...

"Exploring the relationship between Vue checkbox components: parent and

Currently, I am working on a checkbox group where the behavior is such that if the parent checkbox is checked, all the child checkboxes will also be checked. Similarly, if a child checkbox is checked, the parent checkbox should also get checked, and so on. ...

What's the method for validating the spread operator in Typescript?

Is it possible to prevent this code from compiling? (since it currently does...) const bar: { a: string } = { a: '', ...{b: ''} } ...

Adding an object to a dynamic Akita store containing an Array in an Angular application can be accomplished by following these steps

Currently, I am working on storing dynamic values in an Akita store without the need to create a Model. My challenge lies in adding an object to an existing array within the store. As someone who is new to Akita, my initial approach involved deep cloning ...