Utilizing the return value of a MockService in a Jasmine unit test results in test failure

A StackBlitz has been set up with the karma/jasmine loader for you to view test pass/fail results.

The application is functioning correctly.

All my tests are expected to pass without any issues, but I am encountering an unusual error when using a mockservice instead of the actual service in the createspyobject.

component.ts

  getReportFunc(): void {
    this.reportService.getReport(this.urn).subscribe(selectedReport => {
      this.model = selectedReport;
    });
  }

This method makes a simple call to a service to retrieve "getReport". A test will be added to ensure that the report has been retrieved, but currently facing a roadblock due to this issue.

spec.ts

describe("SearchComponent", () => {
  let component: SearchComponent;
  let fixture: ComponentFixture<SearchComponent>;
  let mockReportService;

  beforeEach(async(() => {
      mockReportService = jasmine.createSpyObj(['getReport']);
    TestBed.configureTestingModule({
      declarations: [SearchComponent],
      providers: [
        //ReportService,
            { provide: ReportService, useValue: mockReportService },
...

The problem lies in using

{ provide: ReportService, useValue: mockReportService }
, whereas just using ReportService works fine but restricts running one of the tests. The aim is to create a spy object with
mockReportService = jasmine.createSpyObj(['getReport']);
.

An error message stating

TypeError: Cannot read property 'subscribe' of undefined
can be seen in the StackBlitz. Assistance in resolving this issue to successfully run with a mockservice for testing the getReport subscribe function would be greatly appreciated.

Answer №1

The issue arises from improper usage of jasmine.createSpyObj. There are 2 approaches to address this problem:

  1. Utilize jasmine.createSpyObj correctly:
// Make sure to include the first argument which was missing
mockReportService = jasmine.createSpyObj(ReportService, ['getReport']);


// Additionally, specify how to handle it:
beforeEach(() => {
  [...]
  // When called, return an Observable to ensure success when subscribing
  mockReportService.getReport.and.returnValue(of({}));
  fixture.detectChanges();
});
  1. Avoid using spies

While spies can be handy, they are most beneficial when altering return values for various unit tests. If you simply need a consistent return value, consider using a hardcoded object like this instead:

const mockReportService = {
    getReport: () => of({})
}

providers: [
    { provide: ReportService, useValue: mockReportService },

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

The module 'LoginModule' encountered an error when importing the unexpected value 'LoginRoutingModule'

Greetings! I am currently working on a learning project with Angular 2, where I am developing a test application. While attempting to eagerly load the LoginModule module, I encountered an error message that states: Unexpected value 'LoginRoutingModul ...

Angular2 Error: Cannot have two identifiers with the same name, 'PropertyKey' is duplicated

I am currently developing an application with angular2 using angular-cli. Unfortunately, angular-in-memory-web-api was not included by default. After some research, I manually added the line "angular-in-memory-web-api": "~0.1.5" to my ...

Prevent Click Event on Angular Mat-Button

One of the challenges I'm facing involves a column with buttons within a mat-table. These buttons need to be enabled or disabled based on a value, which is working as intended. However, a new issue arises when a user clicks on a disabled button, resul ...

How can you resolve the error message "No overload matches this call." while implementing passport.serializeUser()?

Currently, I am working on implementing passport.serializeUser using TypeScript. passport.serializeUser((user: User, done) => { done(null, user.id) }); The issue I am encountering is as follows: No overload matches this call. Overload 1 of 2, &ap ...

Gain access to TypeScript headers by typing the request (req) object

Is there a way to access headers in a method that is typed with Express.Request? Here's an example code snippet: private _onTokenReceived(req: Express.Request, res: Express.Response): void { const header: string = req.headers.authorizatio ...

ng-module with tabbed content

I am facing a unique scenario where I have a UserProfileComponent with a tab structure and I want to add tabs from different modules. UserProfileComponent.html <ngb-tabset> <ngb-tab> <app-user-profile-history></app-user-prof ...

Steps to return to the previous roughing from two steps before in Angular 4

Is it possible to navigate back twice in Angular? In a scenario where a user can navigate from view A to view B and then to view C, how can I ensure that clicking the browser's back button from view C takes them directly to view A instead of view B? ...

By default, showcase the value of the first item in the list selected in a mat-selection-list on a separate component

In my project, I have two essential components: 1)list (which displays a list of customers) 2)detail (which shows the details of a selected customer) These components are designed to be reusable and are being utilized within another component called cus ...

In the latest version of Expo SDK 37, the update to [email protected] has caused a malfunction in the onShouldStartLoadWithRequest feature when handling unknown deeplinks

After updating to Expo SDK 37, my original code that was previously functioning started encountering issues with <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0e7c6b6f6d7a23606f7a67786b23796b6c78667f79627a">[email prot ...

Angular: Execute a function once all BehaviorSubject subscriptions have been initialized

In order to facilitate the sharing of parameters across components in my Angular application, I have implemented a "global" service as shown below: import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs/BehaviorSu ...

Loop through the items and provide an observable containing the array

I am currently working with an Observable that contains a User object with an array property called Posts[], and I need to iterate through this array, apply a method to each item, and then return an Observable containing the modified arrays. Here is the c ...

Struggled with the implementation of a customized Angular filter pipe

I have recently developed a custom filter type to sort the notes-list in my application, with each note containing a 'title' and 'message'. Although there are no errors, I am facing issues as the pipe doesn't seem to be working pr ...

A Guide to Creating Java Unit Tests for Nested Methods

Public Class DailyJob(){ public void runJob(ScheduleJob currentJob) { try { int employee = employeeService.getEmployeeNum(); JobPerformance jobPerformance = performanceService.searchJobPerformance(employee); ...

Enhance tns-platform-declarations with NativeScript

I am working on a NativeScript project and I am trying to incorporate the RecyclerView from Android Support Library. I have added the dependency in the app/App_Resources/Android/app.gradle file: // Uncomment to add recyclerview-v7 dependency dependencies ...

Is the user logged in and ready to be redirected to the dashboard through React router?

I am in the process of creating a redirection feature. The goal is to redirect users who are already logged in from the homepage (visible to all) to the dashboard (only visible to logged-in users). Here is my current implementation: export const PublicRo ...

Tips for automatically assigning a default value in a material select within an Angular application

Currently, I have an Angular screen that displays data from a database using a Java REST API. There is a field called esValido which only contains values of 1 and 0 as shown in the initial image. https://i.sstatic.net/R4WCc.png My goal is to implement a ...

Is tsconfig.json necessary for JS libraries without TypeScript to include a .d.ts file when shipping?

I am currently in the process of creating a .d.ts file for an established JavaScript library that does not utilize the TypeScript compiler or include any TypeScript code. Should I include a tsconfig.json file in the library to ensure proper interpretation ...

Can Angular Universal help pinpoint the location of a window reference error?

My Angular Universal project was running smoothly until I added a significant amount of code and included some external npm libraries like Quill. Now, I am encountering a Reference error related to the window object. It seems that every time I reference wi ...

A guide to playing a series of audio files in succession using the Ionic Media plugin

I have been attempting to create a playlist of multiple audio files using the Ionic media plugin from here. However, I am struggling to achieve this without resorting to using a timeout function. Here is my current approach: playOne(track: AudioFile): Pr ...

Using ES6, one can filter an array of objects based on another array of values

Seeking assistance with creating a function to filter an array of objects using another array as reference values. For example: The array containing objects: const persons = [ { personId: 1, name: 'Patrick', lastName: 'Smit ...