Unable to simulate a service and retrieve information in an angular unit test - showing as undefined

In my current project, I have a component that I am trying to write unit tests for. However, when I run the test, I noticed that the value of

console.log('**fav**' + favorite[`isFavorite`]);
shows up as undefined. This indicates that the data I am trying to mock and return from the service is not being returned correctly. I believe that to properly test this, I need to mock the service and ensure that the data is returned so that handleData is called and executed. Can you help me identify where I might be making a mistake?

  ngOnInit(): void {
    this.favoriteService.getData().subscribe(item => {
      if (Object.keys(item).length) {
        this.handleData(item);
      }
    });
  }

  handleData(favorite) {
    console.log('**fav**' + favorite[`isFavorite`]);
    if (favorite[`isFavorite`]) {
      console.log('****1****');
      // some logic
    } else {
      // some logic
    }
  }

Below is the content of my spec file:

describe('FavoritesComponent', () => {
  let component: FavoritesComponent;
  let fixture: ComponentFixture<FavoritesComponent>;
  let stubFavoriteGatewaySpec: StubFavoriteGatewaySpec;
  let spyFavoriteService: jasmine.SpyObj<FavoriteService>;

  const favouriteData = [
    {
      tickerTypeName: 'Market Price',
      type: 'MP',
      headers: ['A', 'B', 'C', 'D', 'E', 'F', 'G'],
      data: [
        [1, '1.020'],
        [0, '-0.250'],
        [-5, '-4.560'],
        [-149, '-149.000'],
      ],
      isFavorite: true,
    }
  ];

  beforeEach(async(() => {
    stubFavoriteGatewaySpec = new StubFavoriteGatewaySpec();
    spyFavoriteService = jasmine.createSpyObj('FavoriteService', [
      'getData',
    ]);
    spyFavoriteService.getData.and.returnValues(of(favouriteData));

    TestBed.configureTestingModule({
      imports: [MatExpansionModule],
      declarations: [FavoritesComponent],
      providers: [
        { provide: FavoritesGateway, useValue: stubFavoriteGatewaySpec },
        { provide: FavoriteService, useValue: spyFavoriteService },
      ],
    })
      .compileComponents()
      .catch(console.log);
  }));

  beforeEach(async(() => {
    fixture = TestBed.createComponent(FavoritesComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  }));

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

Answer №1

//Simulation

const preferredData = {
  tickerTypeName: 'Market Price',
  type: 'MP',
  headers: ['A', 'B', 'C', 'D', 'E', 'F', 'G'],
  data: [
    [1, '1.020'],
    [0, '-0.250'],
    [-5, '-4.560'],
    [-149, '-149.000'],
  ],
  isFavorite: true,
};

//Verification

it(
'should confirm that the favorite is set to true on load',
fakeAsync(() => {
  spyOn(spyFavoriteService, 'getData').and.returnValue(of(preferredData));
  component.ngOnInit();
  expect(component.isFavorite).toBeTruthy();
 //validate your other processes 
})
);

Avoid spying on beforeEach, Use mocking at the test level. Uncertain about the purpose of the handle function, if there is a component variable like isFavorite then it should function correctly.

If using Angular 12, utilize waitForAsync over fakeAsync.

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

Angular: Restarting a material reactive form

I am facing an issue with a form that includes one input from the material library. https://i.sstatic.net/zg0UL.png After submitting the form, I reset it in my submission method like this : onSubmitPriceForm() { // to do...... this.priceForm.r ...

The firebase-generated observable is causing the notorious differ error as it is not iterable

Hey there, I'm encountering an issue that's preventing the route from rendering correctly. I initially thought that unwrapping an observable into an iterable using the async pipe would solve it, but this error indicates otherwise. Sometimes obser ...

An error occurs when trying to use AWS.Comprehend as a constructor in the aws JavaScript SDK

I'm attempting to utilize the Amazon Comprehend API using the AWS JavaScript SDK. However, I keep encountering Uncaught (in promise): TypeError: undefined is not a constructor (evaluating 'new AWS.Comprehend... ' What am I doing incorr ...

Utilizing nested endpoints in Angular resource with a Node.js server

In my Angular application, I have a resource called /cars with the endpoint defined as $resource('/cars/:carsId'); This allows me to retrieve all cars or a specific car. On the server side, I've implemented middleware to ensure that carsI ...

What steps should be followed to effectively incorporate Google Fonts into a Material UI custom theme for typography in a React/TypeScript project

Hey there, I'm currently working on incorporating Google fonts into a custom Material UI theme as the global font. However, I'm facing an issue where the font-weight setting is not being applied. It seems to only display the normal weight of 400. ...

Angular service encounters NotYetImplemented error due to DOCUMENT injection token in SSR

I have a unique Angular SSR app with a special service that utilizes the document. I cleverly utilize the DOCUMENT injection token to provide this essential document for dependency injection. To take a peek at my innovative approach, check out my repo here ...

Combining Angular 2 expressions with jQuery功能

My code snippet is currently functional: <div class="circle" data-value="0.8"%></div> However, I encounter an issue when attempting to bind the attribute: [data-value]="result/100" An error message is displayed: Can't bind to 'da ...

Overriding default styles in an Angular component to customize the Bootstrap navbar

Is there a way to alter the color of the app's navbar when a specific page is accessed? The navbar is set in the app.component.html file, and I am attempting to customize it in a component's css file. app.component.html <nav class="navbar na ...

Encountered an issue with Angular 8 Firebase where an error was thrown at node_modules/firebase/index.d.ts(4369, 38): TS1005 error - expecting a sem

Having some trouble setting up Firebase on my Angular 8 application. I went through the following steps: 1. Deleted my node_modules 2. Ran npm install 3. Ran npm install --save firebase @angular/fire 4. Ran npm run build Encountering this error message: ...

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 ...

What is the best way to input a parameter into an https function when it is invoked from a Swift application?

Currently, integrating stripe into my app using typescript and I have the below function: exports.deleteStripeCustomer = functions.https.onCall((data, context) => { const deleted = await stripe.customers.del( "I need to add the customers ID ...

Implementing binding of JSON API responses to dropdown menus in Angular 4

In my current Angular 4 application, I am faced with the challenge of populating a dropdown menu with data from an API response. Specifically, I am struggling to retrieve the necessary information for each section from the API. The API provides data on C ...

Cannot assign a string literal type in TypeScript to a type parameter that is extending a string literal type

Here is some code snippet that exhibits a specific issue: type FooType = 'Bar'; abstract class Meow<T extends FooType> { baz: T = 'Bar'; } An error is triggered stating Type '"Bar"' is not assignable to type 'T ...

Can you clarify the definition of component initialization in Angular 2+ specifically in relation to the OnInit lifecycle hook?

As per the Angular documentation on Life cycle hooks at Angular.io, the OnInit hook serves to initialize the directive/component after Angular has initially displayed its data-bound properties and set its input properties. But what exactly occurs when it& ...

Surprising Denials Following the Launch of Karma Using NgUpgrade

Currently in the process of implementing ngupgrade into our AngularJS application and consistently encountering unexpected rejection errors while Karma is initializing. The functionality of my app with ngupgrade is running smoothly, but the issue lies wit ...

What could be causing me to receive a 404 error when trying to reload localhost in Angular?

Despite searching for solutions to my issue, I have not found any that have helped me. I have set up my routing in app-routing.module.ts: const routes: Routes = [ { path: 'home', component: LandingpageComponent, canActivate: [AuthGuard] }, ...

What is the best way to generate a variable amount of div elements with constantly changing content using Angular2?

I'm not entirely sure on the process, but I believe ngFor would be used in this scenario. Essentially, my goal is to generate the following div multiple times, with each iteration updating the value inside the brackets from 0 to 1, 2, and so forth... ...

Trouble encountered when using RxJS zip and pipe together

In my Angular Resolver, I am facing a scenario where I need to wait for two server calls. The catch is that the second server call is optional and can be skipped based on user input. This data retrieval process is crucial for loading the next page seamless ...

Choose carefully when to utilize forkJoin

In a particular scenario, I need an application to generate menus based on specific contexts. Here are the definitions for menuA and menuB: // menuA example from a given source menuA() { return [ { a: 'demo1', b: &apo ...

Putting VueJS, typescript, and jest to the test: examining the contents of a dropdown list web-component

Currently, I am in the process of testing a dropdown list within a web component utilized in a VueJS application. My main focus is on checking whether the dropdown list actually contains items fetched through an HTTP query (handled in a vuex store) once t ...