Encountering a service call error during the execution of Angular 2 unit tests using Jasmine

Struggling with testing an angular service, my TypeScript code seems correct but I keep getting an error in my test cases for "this.someFunction.show()" not being a function, even though it exists in my actual service. Here is what I'm attempting to do:

myService.spec.ts

import { dep1, dep......m dep-n } from '../../../../some-modules';
describe('ServiceTest', () => {
let cashPaymentHandlerService : CashPaymentHandlerService;
it('for cash, when pick list enabled, 1 cash drawer, adds payment line', () => {
  methodOne(); //works fine
  methodTwo(false); //works fine
  methodThree(true); //works fine      
  methodFour(); //works fine
  methodFive(1); //works fine
  methodSix(); //works fine
  givenDependanciesAreMocked();
  whenHandlePaymentIsInvoked();
  expect(cashDrawerService.openCashDrawer).toHaveBeenCalled();
});

function givenDependanciesAreMocked(){
  TestBed.configureTestingModule({
 providers: [
   {provide: ServiceOne, useValue: serviceOne},
   {provide: ServiceTwo, useValue: serviceTwo},
   {provide: ServiceN, useValue: serviceN},
   CashPaymentHandlerService
 ]
});
cashPaymentHandlerService = TestBed.get(CashPaymentHandlerService);
}

function whenHandlePaymentIsInvoked() : any {
  cashPaymentHandlerService.handlePayment(cashPaymentRequest);
}

My cash-payment-handler.service.ts file looks like this:

import { dep1, dep......m dep-n } from '../../../../some-modules';

export class CashPaymentHandlerService {
constructor(private service1 : Service1,
          private service2: Service2,
          private serviceN: ServiceN){
}

handlePayment(cashPaymentRequest: CashPaymentRequest) {
  let request = new service1();
  request.initialAmount = this.service2.dataModel.transactionDataModel.balance();
  request.onValueEntered = (response: AmountPromptResponse) => {
    if (!response.cancelled){
      this.addCashPaymentLine(response.value, cashPaymentRequest); // runs fine
    }
  };
  this.serviceN.show(request); //error occurs at this line
}

}

And here's the relevant code snippet from ServiceN.ts:

constructor(
private someController: SomeController){
}

show(options?: NewRequest): void {
if (!options){
  options = new NewRequest();
}

this.someController.show(PromptComponent, options); // PromptComponent imported from some other component
}

I've searched various forums and spent a whole day on this issue without resolution. Any assistance would be greatly appreciated.

Answer №1

After much deliberation, I ultimately found a solution by incorporating mocking functions for the "this.serviceN.show(request);" within my test file "myService.spec.ts". This resolved the issue at hand as the service being tested was interacting with additional components that were not properly referenced during unit testing. By creating mocks for these dependencies, I was able to successfully address the problem.

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 sets apart the utilization of add versus finalize in rxjs?

It appears that both of these code snippets achieve the same outcome: Add this.test$.pipe(take(1)).subscribe().add(() => console.log('added')); Finalize this.test$.pipe(take(1), finalize(() => console.log('finalized'))).sub ...

Tips for customizing the event target appearance in Angular 2?

After following the steps outlined in this particular blog post (section 3, event binding), I successfully added an event listener to my component class. I can confirm that it responds when the mouse enters and exits. <p class="title" (mouseenter)="unf ...

When multiple input fields with an iterative design are using the same onChange() function, the specific event.target.values for each input

I'm in the process of developing a dynamic select button that adjusts based on the information entered into the iterative input fields I've set up. These input fields all utilize the same onChange() function. for (let i = 0; i < selectCount; i ...

Using Observable and EventEmitter to efficiently transfer data between parent and child components in Angular

I am struggling with the following structure: Main component (displays items using item-service) Panel component (includes search components) SearchByTitle component (with input field for title of items) SearchBySomething component (with input field ...

Guide on utilizing a module to define numerous elements in Angular 6

I am trying to use the joke.module.ts module to specify multiple components. Starting with JokeComponent in joke/joke.module.ts within the src/app directory. import { Component } from '@angular/core';/ @Component({ selector: 'joke', ...

The type '{}' does not contain a property named 'map'

Recently delving into TypeScript, and I'm curious about the process of typing an axios response when storing it in a state variable. I've initiated a basic API call from App.tsx, which returns the following object: {data: {…}, status: 200, s ...

Maximizing Azure Web App capabilities to host multiple applications

I have developed an app using ASP .NET Core MVC + Angular and now I need to deploy it for three separate customers. Each customer currently has their own database. Is it feasible to create multiple sites within a single Azure web app (such as mysite.com/ ...

Link a YAML file with interfaces in JavaScript

I'm currently learning JavaScript and need to convert a YAML file to an Interface in JavaScript. Here is an example of the YAML file: - provider_name: SEA-AD consortiumn_name: SEA-AD defaults: thumbnail Donors: - id: "https://portal.brain ...

Issue encountered in Angular 2 rc.5 where the page fails to refresh after upgrading from rc.4

I recently updated my app from rc.4 to rc.5 and now I'm facing an unusual issue. Upon visiting localhost:8080, I am correctly redirected to localhost:8080/browse. However, when I refresh the page, I receive the error message: Cannot GET /browse. Pri ...

Why aren't Dependencies like RxJS being installed from package.json in the Dockerfile?

As I try to containerize my application for deployment on GCP, I have encountered an issue during local testing. It seems that the rxjs module (and possibly others) listed in package.json is not being installed properly. When building my Dockerfile, I rec ...

Nock does not capture the requests - Error: Failed to resolve address ENOTFOUND

Let me provide an overview of the structure in place. Jest is utilized for executing the testing process. Within my jest.config.json file, I incorporate the following line: "globalSetup": "<rootDir>/__tests__/setup.js", Inside setup.js, you will ...

I'm seeing an issue where my SafeResourceUrl is being displayed as undefined within a function of the identical class

export class ClassName implements OnInit { url: string = "{{'content.url' | translate}}"; urlSafe: SafeResourceUrl; constructor(public sanitizer: DomSanitizer, private translate: TranslateService) { } ngOnInit() { ...

The health check URL is experiencing issues: Unable to locate any routes

I am currently developing a .net Core 2.2/Angular 8 application and recently came across the HealthCheck feature. I decided to incorporate it into my application, so here is a snippet from my Startup.cs file: using HealthChecks.UI.Client; using Mi ...

Error message: Issue with AWS Serverless Lambda and Angular - TypeError: express function not defined

I'm encountering an issue when trying to deploy my application from localhost:4200 to AWS serverless Lambda. The error in cloudwatch logs is causing a 500 {"message": "Internal server error"} response when I access the URL. My understanding of AWS is ...

Angular 11 issue: Unable to display image on the webpage

When I try to view my image by directly using the URL in the src tag, it works fine. However, when I attempt to load it dynamically, an error is thrown. Even using [src]="img.ImagePath" method gives me the same response Here is the error logged ...

Ways to mandate a field to only be of type object in TypeScript

I need to design a type that includes one mandatory property and allows for any additional properties. For instance, I require all objects to have an _id property of type string. {_id: "123"} // This will meet the criteria {a: 1} // This will not work as i ...

What is the best method for conducting comprehensive testing of all projects and libraries within NestJS (nx)?

Our NestJS project has been established with multiple libraries through Nx. We have successfully run tests on individual projects/libraries using the following command: npx nx test lib1 --coverage While this method works well, we are faced with numerous l ...

Tips for transforming an Observable stream into an Observable Array

My goal is to fetch a list of dogs from a database and return it as an Observable<Dog[]>. However, whenever I attempt to convert the incoming stream to an array by using toArray() or any other method, no data is returned when calling the retrieveDo ...

In TypeScript, the 'onChange' is declared multiple times, therefore this particular usage will be scrutinized carefully

Within my React project, I am utilizing material-ui, react-hook-form, and Typescript. However, I encountered an error in VSCode when attempting to add the onChange function to a TextField component: 'onChange' is specified more than once, resul ...

How to use Web3 in conjunction with a Paymaster to execute a smart contract transaction and have the Paymaster cover the gas fees?

Seeking a method to call a smart contract function using web3js in an Angular 17 project, with gas fees covered by a paymaster-contract. How can I make this happen? web3 version: 4.6.0 Angular Version: 17 network: zkSync const web3 = new Web3(window ...