Error encountered while testing karma: subscription function is not recognized

I encountered an issue with my karma unit test failing with the following error message.

"this.gridApi.getScaleWidth().subscribe is not a function"

GridApi.ts

export class GridApi {

    private scaleWidthSubject = new BehaviorSubject<{value: number}>({value: 0});

    public getScaleWidth(): Observable<{value:number}> {
        return this.scaleWidthSubject;
    }
}

GridComponent.ts

export class GridComponent implements OnInit, OnDestroy, AfterViewInit {

    private subscribeToValueChanges() {        
        this.scaleWidth$ = this.gridApi.getScaleWidth().subscribe( width => {
        this.scaleWidth = width.value;
    });

 }
}

Component.spec.ts

describe('GridComponent', () => {

beforeEach(async () => {
    const mockGridApiService = jasmine.createSpyObj("GridApi", {
        getScaleWidth () : Observable<{value: number}> {
            let scaleWidthSubject = new BehaviorSubject<{value: number}>({value: 0});
            return scaleWidthSubject.asObservable();
        }
    });
}

await TestBed.configureTestingModule({
    providers: [ { provide: GridApi, useValue: mockGridApiService} ],
    imports: [
        HttpClientModule
    ],
    declarations: [ GridComponent ]

})
}

Can someone guide me on what the mock getScaleWidth() should return in order to successfully pass the test? I seem to be missing something here.

Answer №1

describe('GridComponent Test Suite', () => {
  const mockGridService = jasmine.createSpyObj<GridApi>('GridApi', ['getScaleWidth'])

  beforeEach(() => {
    mockGridService.getScaleWidth.and.returnValue(of({ value: 0 }));
  });

  await TestBed.configureTestingModule({
    providers: [ { provide: GridApi, useValue: mockGridService} ],
    imports: [HttpClientModule],
    declarations: [ GridComponent ]
  })

  it('should successfully call getScaleWidth from the service', () => {
    // The triggering component function for the service call is private 
    // Simulate the call from the component
  
    expect(mockGridService.getScaleWidth).toHaveBeenCalled(); 
    mockGridService.getScaleWidth().subscribe(response => {
       expect(response.value === 0)
    }) 
  })
}

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

What is the best way to display just one record that has the lowest score out of all the records?

I need help with displaying only 1 record from the DL list that has the lowest score, instead of showing all records. In the example on stackblitz, you can see that for the first record, the DL scores are: 54, 20, and updated. Instead of displaying all 3 ...

Angular - Automatically filling in an empty input field upon dropdown selection

My goal is to create a DropdownBox that will automatically fill input fields based on the selected value. For example, selecting "Arnold" from the dropdown will populate another textbox with "Laptop". How can I accomplish this? { name:'Arnold', i ...

Error occurs when using JSON.stringify with a Typescript array map

When running this code snippet in Typescript: [].map(JSON.stringify); An error is being thrown: Argument of type '{ (value: any, replacer?: ((key: string, value: any) => any) | undefined, space?: string | number | undefined): string; (value: a ...

Developing versatile form elements with Formik and the Yup library for React and Vite

I'm currently working on a React and Vite project where I'm trying to implement reusable form components using Formik and Yup, but I haven't been able to achieve it yet. I've created a component called <AppInputField/>, which is e ...

The ƒ character doesn't seem to be a match for the JavaScript regex

I am facing a requirement to only allow (extended) ASCII characters in my input. As a solution, I've implemented a JavaScript regex pattern like this: /^[\x20-\xff]+$/.test("helloê¿£×جáƒ") However, this doesn't work as expect ...

Using Dropbox for seamless navigation

My navigation using Dropbox is not redirecting to the selected page as expected. Below, I have provided code and a demo for your reference. App Routing Module import { NgModule } from '@angular/core'; import { CommonModule } from '@angular ...

What is the best way to insert an <image> tag into the SVG DOM?

Currently, I am facing an issue with adding a background image to the generated SVG DOM in my web page. The user interacts by drawing an SVG doodle on top of a jpg image using Raphael. After the user is done with their drawing, I want to enable them to sa ...

Is there a way to alter the background color of a Material UI card when it is being hovered over

I'm currently using material ui with react and I have a question regarding the background color of my card component when a user hovers over it. Can someone help me figure out how to achieve this? For reference, here is the live code link in CodeSand ...

group array by month and year

I have an array structured like this var dataset = [[1411151400000,1686],[1428604200000,1686],[1411151400000,1686]....] The goal is to group the data based on months and calculate the total sum of values for each month. The expected final output should ...

Failed Cross-Origin Request Sharing in AngularJS 1.4

I'm currently working with AngularJS version 1.4.3 and here is the code snippet I am using: angular .module('app', []) .run(run); function run($http) { a = $http({ method: "GET", url: 'http://127.0.0 ...

Is there a way to incorporate promises into an endless loop while adding a delay in each iteration?

require("./getSongFromSpotify")().then(a => { require("./instify")(a.artist,a.name).then(r => { if (r.status === "ok"){ console.log("saved") }else{ console.log(" ...

The functionality to save user likes in React is not properly functioning on the like button

I created a like button in React that saves my choices, but it seems to be not saving the choices of other users. Additionally, it doesn't appear to restrict only authenticated users from marking likes. Can someone please help me identify what I' ...

Utilize Angular's Router by injecting it into CanActivateFn for use within runInInjectionContext

I am facing a situation where a guard needs to retrieve data asynchronously and then decide whether to redirect the user using URLTree based on that value. The implementation is quite straightforward: export const otapGuard: CanActivateFn = async (route, ...

The JavaScript-set value in a form field is not being transmitted to the PHP script within the $_POST array

Struggling to pass a JavaScript value to a .php script, and then on to a .txt script. It works fine with regular numbers, but when trying with the variable it fails, leaving the .txt file blank. Despite extensive research online, I can't seem to get i ...

How to send parameters to the jQuery delete button click event handler

Here is the jQuery code I am working with: $('#btnDelete').click( function() {//Do the delete here via jquery post}); In my table, each row has a delete button like this: <a id="btnDelete">Delete</a> I need to pass parameters to t ...

Tips for saving a JavaScript object into a JSON file

Let's discuss how to save the following data: myJSONtable into a JSON file using the following method: fs.writeFile('./users.json', JSON.stringify(myJSONtable, null, 4), 'utf-8', function (err) { if (err) throw err ...

Limit the type to be used for a particular object key in TypeScript

My pet categories consist of 'dog' and 'cat' as defined in the Pet type: type Pet = 'dog' | 'cat' I also have distinct types for allowed names for dogs and cats: type DogName = 'Jack' | 'Fenton&apos ...

Issues with command functionality within the VS Code integrated terminal (Bash) causing disruptions

When using Visual Studio Code's integrated terminal with bash as the shell, I have noticed that commands like ng and tsc are not recognized. Can anyone shed some light on why this might be happening? ...

Error retrieving data from the ngresource properties resource

In the code snippet below, I have a simple factory that requests a json object containing location information. The requests are successful and the data is present in the object. However, there seems to be a scope problem as I am unable to access the prope ...

The issue of "Invalid arguments passed to jsPDF.text" encountered while using jsPDF on an nginx server

In my project admin, I have successfully implemented jspdf. The admin panel works perfectly fine on localserver. However, when I deploy it to a live nginx server, the server side throws an error: Error: Uncaught (in promise): Error: Invalid arguments passe ...