Spying on an Angular service with additional parameters present

Is there a way to monitor and imitate a service using another service parameter? For instance, the new Authservice includes this parameter:

export class AuthService{
    constructor(public serviceAbcd: ServiceAbcd) {}

This serves as an illustration without a constructor parameter on AuthService.

describe('Component: Login', () => {

  let component: LoginComponent;
  let service: AuthService;
  let spy: any;

  beforeEach(() => {
    service = new AuthService();
    component = new LoginComponent(service);
  });
    
  it('needsLogin returns true when the user has not been authenticated', () => {
    spy = spyOn(service, 'isAuthenticated').and.returnValue(false);
    expect(component.needsLogin()).toBeTruthy();
    expect(service.isAuthenticated).toHaveBeenCalled(); 
  });

  afterEach(() => { 
    service = null;
    component = null;
  });

});

We are exploring testing without Testbed https://dev.to/angular/unit-testing-in-angular-to-testbed-or-not-to-testbed-3g3b

Answer №1

If you want to access a service in Angular, you can utilize angular's Testbed and inject the service.

import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';

describe('Component: Login', () => {
  let service: AuthService;
  beforeEach(waitForAsync(() => {
    TestBed.configureTestingModule({
      imports: [
      ],
      declarations: [LoginComponent]
    })
      .compileComponents();
    service = Testbed.inject(AuthService);
  }));
  it('checks if needsLogin returns true when the user has not been authenticated', () => {
    spy = spyOn(service, 'isAuthenticated').and.returnValue(false);
    expect(component.needsLogin()).toBeTruthy();
    expect(service.isAuthenticated).toHaveBeenCalled(); 
  });

  afterEach(() => { 
    service = null;
    component = null;
  });
}

Answer №2

Is it possible for you to execute service = new AuthService()? Does it not give an error message indicating that an argument is required?

Give this a shot:

service = new AuthService({/* provide mock ServiceAbcd here */});

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

Error: AsyncPipe received an invalid argument of type '[object Object]'. This has caused an error due to an invalid pipe argument

I'm currently working on developing a contact management system that includes CRUD operations using Angular 8 and Spring Boot. Every feature is functioning correctly except for the search functionality. My goal is to search for data based on a specifi ...

Arranging the output of a Typescript project

I'm currently advocating for Typescript to be implemented in our web application. Can anyone provide insight on the best method for structuring Javascript output files? Should they be excluded from source control? And when it comes to testing, is it p ...

What is the reason behind the equality comparison between number[][number] and number in TypeScript?

https://i.stack.imgur.com/htnkb.png type Test = number[][]; // The Test type will be inferred as 'number' based on the image above. Can you explain why number[] is considered an index signature type with a signature of 'number'? ...

Incorporate TypeScript with Angular 2 to construct a dictionary with <key, value> pairs. Then, utilize a JSON file to populate the dictionary with data

I am in need of assistance with creating a dictionary or list with a specific structure. I have prepared a json file within my angular 2 project, and I would like to load this data into the dictionary that I am creating. Sample content from my Json file: ...

Ensure that the query value remains constant in Express.js

Issue: The query value is changing unexpectedly. // url: "http://localhost:4000/sr?q=%C3%BCt%C3%BC" export const search = async (req: Request, res: Response) => { try { const query = String(req.query.q) console.log("query: &quo ...

Exploring Angular's APP_INITIALIZER: Comparing Promises and Observables

I have implemented an Angular v4 application where I need to retrieve settings from the server before the app starts. This is achieved using the APP_INITIALIZER: { provide: APP_INITIALIZER, useFactory: initializeSettings, deps: [SettingsService], ...

Saving data from Material UI forms in TypeScript

Is there an effective method for storing values entered into the text fields on this page? const AddUserPage = () => ( <div> <PermanentDrawerLeft></PermanentDrawerLeft> <div className='main-content'> < ...

What is the best way to incorporate @types dependencies into my Angular 2 project?

After installing Twitter's Bootstrap using 'npm install @types/bootstrap --save', my package.json dependencies are as follows: { "dependencies": { "@angular/common": "~2.4.0", "@angular/compiler": "~2.4.0", "@ang ...

Transitioning to TypeScript has brought the promise of imports returning once again

I've been facing some challenges while migrating my extensive project to TypeScript, particularly with handling imports. Being relatively new to programming, I'm unsure if my previous approach was considered bad practice. Previously, I organized ...

Is it better to keep a lengthy array in the back-end or front-end storage?

I'm facing a dilemma in my angular application. I have a lengthy array that I need to access easily from the front-end without causing any slowdowns. There are various options available, but I'm unsure which one would be the most efficient. Shoul ...

In Typescript, is there a way to retrieve the name of an object when working with object types?

I am working on creating a for() loop to check the first field in my template with the status INVALID and I need to retrieve the name of this object. This is what I have tried so far: for(var mandatoryField in form.controls){ if(form.controls[mandato ...

How do I go about updating my custom element after making a REST call using @angular/elements?

Looking for some assistance with my latest creation: import { Component, ViewEncapsulation, OnInit, } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { BehaviorSubject } from 'rxjs'; @C ...

Steering clear of the generic Function type in React with TypeScript

Can anyone help me find a guideline that prohibits the use of "Function" as a type? myMethod: Function; I have searched but couldn't locate any information on this. Appreciate any suggestions :) ...

Can you explain the distinction between inheritance and union types in regards to portraying polymorphism?

Exploring union types in Typescript, I have discovered a new way to showcase polymorphism without relying on inheritance. In my previous Java background, I would typically approach it like this: interface Emotion { display(): string; } class Joy impleme ...

What is the step-by-step guide for implementing an access limiter on an interface

When attempting to modify the access level on an interface in Typescript, I encountered an error stating 'cannot appear in type member.' After removing the access limiter on the interface and implementing it, I tried changing the access limiter o ...

What is the best way to calculate the product of decimal numbers within a TypeScript Number variable?

Imagine you have a number, for example 288.65, and you want to multiply it without the decimal point in order to obtain the result of 28865. However, when attempting to achieve this by using console.log(288.65 * 100), the output is not as expected, showin ...

Verify Angular Reactive Form by clicking the button

Currently, I have a form set up using the FormBuilder to create it. However, my main concern is ensuring that validation only occurs upon clicking the button. Here is an excerpt of the HTML code: <input id="user-name" name="userName" ...

Ways to distinguish a type that may not have a defined value

What is the most effective method to define an interface that may be undefined? Currently, I have the following setup but I am seeking a more sophisticated and succinct alternative. interface RouteInterface { path: string; test: boolean; } type TypeOr ...

Using React hooks and Typescript: I was expecting to see an assignment or function call, but instead, an expression was

After working as a React developer for quite some time, my workplace recently introduced Typescript, which I am still getting familiar with. I implemented a custom hook for managing cookies, but the function it returns is generating an error. Here's ...

Tips for injecting scripts into the head tag after an Angular component has been loaded

Currently, I am facing an issue with a script tag containing a Skype web control CDN. The script has been placed in the head section of my index.html file, but it is being called before the component that needs it has finished loading. Does anyone have a ...