How to effectively test @input using Jasmine: Anticipated Object did not match undefined

Having trouble with this error. There seems to be something missing but can't pinpoint what it is. The task at hand is simple: just test this basic component. Let's take a look:

import { Component, OnInit, Input } from '@angular/core';
    import { ButtonModel } from './model/button.model';

    @Component({
      selector: 'app-button',
      templateUrl: './button.component.html',
      styleUrls: ['./button.component.scss']
    })
    export class ButtonComponent implements OnInit {
      @Input() public button: ButtonModel;

      constructor() { }

      public ngOnInit(): void {
      }

      public getClasses(): [string, string] {
        return [
          this.button.Size,
          this.button.Color
        ];
      }
    }
    

And the tests:

import { Spectator, createHostFactory } from '@ngneat/spectator';
    import { RouterTestingModule } from '@angular/router/testing';
    import { ButtonComponent } from './button.component';
    import { MockComponent } from 'ng-mocks';


    describe('[ButtonComponent]', () => {
      let spectator: Spectator<ButtonComponent>;
      const createHost = createHostFactory({
        component: MockComponent(ButtonComponent),
        imports: [RouterTestingModule]
      });

      beforeEach(() => {
        spectator = createHost('<app-button></app-button>');
      });

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

      it('should get default classes', () => {
        expect(spectator.component.getClasses()).toEqual(['big', 'primary-theme-color']);
      });
    });
    

And the HTML:

<button [ngClass]="getClasses()">
      {{button.Text}}
    </button>
    

Now, let's address that error:

Encountered a mismatch between expected and actual values. Error: Expected undefined to equal [ 'big', 'primary-theme-color' ]. at at UserContext. (http://localhost:9876/_karma_webpack_/src/app/shared/components/button/button.component.spec.ts:24:46) at ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-evergreen.js:359:1) at ProxyZoneSpec.onInvoke (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-testing.js:308:1)

Answer №1

If you're utilizing spectator for testing purposes, feel free to check out the tool's documentation here: https://github.com/ngneat/spectator

In your particular situation, you should use

spectator.setInput('button', {Text: 'my text', Size: '...', Color: '...'})
before your expect

Answer №2

Experimenting without a host component and adjusting button property values proved successful for me,

  let reviewer: Reviewer<ButtonComponent>;   
  const constructComponent = constructComponentFactory(ButtonComponent);

  beforeEach(() => {
    reviewer = constructComponent({
      props: {
        button: {Type: "large", Style: 'blue'}
      }
    });
  });

  it('should be created', () => {
    expect(reviewer.component).toBeTruthy();
  });

  it('should receive default styles', () => {
    expect(reviewer.component.getStyles()).toEqual(['large', 'blue']);
  });

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

Retrieve data from a web api at regular intervals using Angular observables and subscription

My Launch method is designed to start an engine by taking parameters and returning the instance name once started. After that, I need to periodically query another service every 2 seconds to check if the status has changed to either "Succeeded" or "Faile ...

The server failed to respond to the Angular HTTP request

To store data in my database, I have created a function in my component.ts file that invokes a service: ajoutText(newtext: String) { this.dataService.sendtext(newtext); } On the HTML side, it looks like this: <form class="form"> <mat-form-f ...

Creating a personalized Cache Module in Nest JS involves implementing a custom caching mechanism tailored to

I need help with implementing a custom CacheModule in NestJS. The guide only shows how to connect the cache directly to the main module of the AppModule application. What is the correct way to define and implement a custom cache module? My attempt at crea ...

Is it possible to drag the div container in HTML to resize its width from both left to right and right to left?

After posing my initial inquiry, I have devised a resizing function that allows for the expansion of a div's width. When pulling the right edge of the div to resize its width from left to right, is it possible to adjust the direction or how to resize ...

What is the best way to send an XML body using Angular 5 with POST method?

I am currently developing an Ionic application that needs to make REST API calls with XML as the body. However, I am facing issues in getting the call to post with XML. This is my LoginProvider where I utilize DOMParser to parse data to XML before sending ...

The application is experiencing compilation issues following the creation of mime-type.validator.ts. This problem has been reported by one author

I originally created a file called mime-type.validator.ts. Although I haven't used this file yet in my application, it does exist within my project. However, now my application is failing to compile and displaying the following error message: Faile ...

What is the correct way to specify the type in my functional component?

I was trying to define the type in my component in a different way, I know it can be done using classes but is there a way to achieve this with functional components without exporting the interface? Despite my extensive research, I couldn't find any r ...

Unable to include a header in an Angular 2 HTTP request

Having trouble with the http request headers while using the following code snippet: let authToken = new Headers() authToken.append("Authorization", "xyz"); this.http.get("http://localhost:8081/hello", {headers: authToken}) .subscribe((response) =& ...

Pagination and Rowspan features malfunctioning in Material Table

Currently, I'm encountering a problem when trying to paginate a material table with rowspan. The binding of the rowspan attribute works correctly by itself. However, once pagination is implemented, it results in the duplication of values. For instance ...

Creating a generic anonymous class in TypeScript can be achieved by specifying the class body

The title might be a bit misleading, but I'm struggling to articulate my issue. I aim to pass a generic class (or just the class body) as an argument to a function. The provided class should then infer its generics automatically. class Builder<EX ...

Transferring AgGrid context in a functional React component

I have been working on a component that utilizes AgGrid to display a table, with the data sourced from a Redux selector. My goal is to include a button within a cell in the table that triggers an action based on the specific row's data. However, I a ...

Unable to find the required dependency: peer tslint@ "^5.0.0 || ^6.0.0" in [email protected] node_modules/codelyzer development codelyzer@ "^5.1.2" from the main project directory

Struggling to create my angular project, I've attempted updating @angular/core and even deleted the node modules folder and reinstalled it. I also played around with the version of my node and npm, but nothing seems to work. Here's the error: [1 ...

What's the best way to declare a component that is intended to be used across all pages of my application?

I have a HeroLogoComponent that is included in the header of every page in my app. It is declared in the app.module like this: @NgModule({ declarations: [ MyApp, HeroLogoComponent, ], ... Based on what I have read in the Angular documentation, usin ...

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

Creating a new endpoint within the Angular2 framework using typescript

I am brand new to Angular2 and I would like to streamline my API endpoints by creating a single class that can be injected into all of my services. What is the most optimal approach for achieving this in Angular2? Should I define an @Injectable class sim ...

shifting the angular directives to alternate the bootstrap class of hyperlinks

I have a collection of hyperlinks displayed on my webpage. <a href="#" class="list-group-item list-group-item-action active" routerLink='/route1' >Explore First Link</a> <a href="#" class="list-group-item list-group-item-action" r ...

Transferring data between pages in Next JS using App Route and Typescript

Seeking assistance to extract data from an array on one page and display it on another page. I am working with NextJs, Typescript, and AppRoute. Code in app/page.tsx: import Image from 'next/image' import Link from 'next/link' const l ...

"Unindexing data in Angular: A step-by-step guide

Can someone help me figure out how to delete an item by index in Angular? I have a parameter and a remove button, but when I tried putting my parameter inside the remove button it didn't work. How can I fix this? deleteRowFiles(rowIndex: number){ th ...

Creating reusable functions in VueJS that can be accessed globally by all child components

Looking for assistance in setting up a universal function that can be accessed across all my Vue files. For example, when using this code snippet in a Vue file: @click="ModalShow.show('my-create')" I have defined the following constan ...

Having difficulty overriding the Content-type in http.put while using Angular RC2

I'm encountering an issue in the latest version of rc2 that didn't exist in older versions and I'm unsure if it's a bug or something I'm doing wrong. The problem arises when making a http.put request where I need to set Content-ty ...