Testing Angular with Jasmine: The spy should have been called as expected

Seeking assistance for a persistent issue that has been troubling me.

I am currently working on unit tests for a component I developed, and no matter what I try, I can't seem to resolve the recurring problem of an "Expected spy getTopRatedMedia to have been called" message.

This test is supposed to verify if a service method is being invoked, but I keep getting the log message "Expected spy getTopRatedMedia to have been called."

media-list-page.component.ts

Async function onMediaChange(media: string): Promise<void> {
    // Component logic here.
}

media-list-page.component.spec.ts

Focusing on testing the functionality of the api method getTopRatedMedia()

mocks.ts

@Injectable({
  providedIn: 'root',
})
export class MockedApiService {
  // Function returning mocked object
}

Appreciate any assistance provided :)

Answer №1

Are you certain that the first condition in the if statement is true? Does it enter the block

if(!this.searchParam || this.searchParam.length <= 2)
?

If so, it seems like you need to ensure that the promises are resolved before proceeding with the assertions.

//// TEST FAILURE ////
  it('should execute the api method getTopRatedMedia()', async() => { // add async here
    const fixture = TestBed.createComponent(MediaListPageComponent);
    fixture.detectChanges();
    const compiled = fixture.nativeElement;
    spyOn(api, 'getTopRatedMedia').and.callThrough();
    component.searchParams = ''; // this line might not be necessary, but ensure it is within the first if block
    component.onMediaChange('shows');
    fixture.detectChanges();
    await fixture.whenStable(); // wait for the completion of await this.stateService.getConfiguration();
    await fixture.whenStable(); // wait for the completion of await this.api.getTopRatedMedia(media);
    expect(api.getTopRatedMedia).toHaveBeenCalled();
  });

You may try running the test with just one await fixture.whenStable() instead of two as the second one could be optional.

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

Required Ionic form field alert

Currently, I am developing a new app using ionic 3 and I am facing an issue with making inputs mandatory in my ionic-alert controller. Despite going through the ionic-component documentation and api documentation, I couldn't find a solution on how to ...

Sortable layouts and tables in Ionic 3

I found a great example of an Ionic table that I'm using as reference: https://codepen.io/anon/pen/pjzKMZ <ion-content> <div class="row header"> <div class="col">Utility Company Name</div> <div c ...

Navigating the proper utilization of exports and subpaths in package.json with TypeScript

As a newbie in creating npm packages using TypeScript, I've encountered some issues that I believe stem from misinterpreting the documentation. Currently, I am working with Node 16.16.0 and npm 8.13.2. Here is the structure of my project: src/ ├─ ...

Make sure to wait for a Promise to resolve before initiating another Promise within a for loop in Angular

Issue: I am trying to call multiple APIs in sequence within a for loop and need each API call to wait for the previous one to resolve before making the next call. Within my code, I have a for loop that calls a Get API to generate documents on the server s ...

Steps to set angular for all items in the dropdown menu:

I am currently working on implementing a dropdown feature within my Angular application. The dropdown will display a list of shops, and when a shop is selected, it will show the content related to that particular shop. I need to add a new item called "ALL ...

REDUX: The dispatch function is failing to update the store

Working on a project developing a chrome extension that involves dispatching functions in popup.tsx. However, the store does not update when I try to dispatch. Interestingly, the same code works perfectly fine in the background page. Any suggestions on wha ...

Encountering a "Duplicate identifier error" when transitioning TypeScript code to JavaScript

I'm currently using VSCode for working with TypeScript, and I've encountered an issue while compiling to JavaScript. The problem arises when the IDE notifies me that certain elements - like classes or variables - are duplicates. This duplication ...

solution for downloading large files from authenticated endpoint that works across multiple web browsers

I'm currently on the lookout for a solution to download large files (around 2 - 4 GB) from a bearer token protected api endpoint that is compatible with all common browsers including IE 11, Chrome, Firefox, Android Browsers, and Safari. I want it to w ...

Creating global variables in NodeJS allows you to access and modify data

Currently, this construct is being utilized to create a global LOG: declare global { let LOG: Logger; } // eslint-disable-next-line @typescript-eslint/no-namespace declare namespace globalThis { let LOG: Logger; } globalThis.LOG = new Logger(); It f ...

I'm uncertain about the appropriate RabbitMQ subscription endpoint with STOMP

I'm using spring-boot-starter-amqp library to send messages to RabbitMQ. I've configured the exchange as spring-boot-exchange and set the routing key as group.n (where n is variable). I'm trying to retrieve these messages in Angular using n ...

When you click on the mat-tab label, it will act as a link and directly open the

I am facing an issue where I have 4 mat-tabs and I want to add one more tab. This additional tab will act as a label that, when clicked, opens a provided link. I have tried the following code but it is not working: <mat-tab label="Statistik ...

Troubleshooting Node Server Startup Problems in AngularJS 2

I've been working on an Angular 2 sample app that was functioning perfectly until recently. However, when I attempt to run it now, a particular error pops up in the terminal: app/idea.ts(3,8): error TS2304: Cannot find name 'date'. The con ...

Implementing Typescript for React Navigation: Configuring navigationOptions effectively

Within a React Native app utilizing React Navigation, I am working on a screen component where I aim to set the title based on given parameters using the navigationOptions property like so: static navigationOptions = ({navigation}) => ({ title: nav ...

Tips for successfully passing function variables as parameters to Angular 2 HTTP subscribe callbacks

I attempted this.propositionService.addProposition(this.proposition) .subscribe(this.addSuccessCallback, this.addFailureCallback); The issue I am encountering is that both addSuccessCallback and addFailureCallback do not have acces ...

Get rid of the "No data" tag from the nz-table within a Simple Component

(Apologies for any language errors, English is not my native tongue) I'm working on a web page utilizing the smart and dumb components architecture. The issue I'm facing is that after fetching data from an API in my smart component, the table in ...

Tips for synchronizing response JSON with TypeScript interface in Angular 6

I am retrieving a list of files that have been uploaded from a backend endpoint, and it comes back in this format: [ { "filename": "setup.cfg", "id": 1, "path": C:\\back-end\\uploads\\setup.cfg", ...

Customizing the default font color in Angular Material

I am currently navigating through theming in Angular Material and feeling a bit disoriented. I have implemented the prebuilt indigo-pink theme by importing it into my styles.scss as shown below: @import "~@angular/material/prebuilt-themes/indigo-pink.css" ...

Angular: handling HTTP errors gracefully in the chain of operations

I am facing an issue where I need to treat specific HTTP error codes as non-errors and handle their responses normally. To achieve this, I implemented an HttpInterceptor to catch 500 status codes and return the original response that Angular stores in erro ...

The password encryption method with "bcrypt" gives an undefined result

import bcrypt from 'bcrypt'; export default class Hash { static hashPassword (password: any): string { let hashedPassword: string; bcrypt.hash(password, 10, function(err, hash) { if (err) console.log(err); else { ha ...

Can someone explain how to create a Function type in Typescript that enforces specific parameters?

Encountering an issue with combineReducers not being strict enough raises uncertainty about how to approach it: interface Action { type: any; } type Reducer<S> = (state: S, action: Action) => S; const reducer: Reducer<string> = (state: ...