Encountering errors when examining local variables during unit testing on an Angular component

If we have 2 components, namely AppComponent and TestComponent. The TestComponent is being called using its directive in the HTML template of the AppComponent. Within the TestComponent, there is an @Input() property named myTitle.

Unit testing is being performed solely on the TestComponent. A random value is passed for the title within the test. Below is the code snippet:

app.component.html

<span><app-test [myTitle]="title"></app-test></span>

app.component.ts

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})

export class AppComponent{
    title = {name: 'hello-world'};
}

test.component.html

<p>test works!!{{myTitle.name}}</p>
<button (click)="onClick()">Click Please !!!</button>

test.component.ts

@Component({
    selector: 'app-test',
    templateUrl: './test.component.html',
    styleUrls: ['./test.component.css']
})

export class TestComponent implements OnInit{
    @Input() myTitle;
    filter;
    constructor(){

    }

    ngOnInit():void{
        this.myTitle.name = "Hi!!";
    }
    onClick(){
       this.filter="GokuSSj3";
    }
}

test.component.spec.ts

describe('Test component',() =>{
    let temp;
    let component: TestComponent;
    let fixture: ComponentFixture<TestComponent>;

    beforeEach(async(() =>{
       TestBed.configureTestingModule({
           declarations: [TestComponent],
           schemas: [NO_ERRORS_SCHEMA]
       }) 
       .compileComponents();
    }));

    beforeEach(()=>{
        temp = {name: "Heloooo"};
       fixture = TestBed.createComponent(TestComponent);
       component = fixture.componentInstance;
    });

    it('should check First',()=>{
       component.myTitle = temp;
       console.log(component.myTitle.name);
       console.log(temp.name);

       fixture.detectChanges();

       console.log(component.myTitle.name);
       console.log(temp.name);
       expect(component.myTitle.name).toEqual(temp.name);
    });

    it('should check whether onClick is called on button click or not and also the value of filter',()=>{
       component.myTitle = temp;
       spyOn(component,'onClick');
       fixture.detectChanges();

       let btn = fixture.debugElement.query(By.css('button'));
       btn.triggerEventHandler('click',null);

       fixture.whenStable().then(()=>{
          expect(component.onClick).toHaveBeenCalled();
          expect(component.filter).toEqual("GokuSSj3");
    });
});

The second test case indicates an error: Expected undefined to equal 'GokuSSj3'. Why does this happen despite onClick being triggered?

Feedback from experienced community members on how to enhance the question is greatly appreciated as I am new here!

Answer №1

By adding a spy on the onClick function, you are preventing it from firing and updating the value of the filter.

To see the actual value change, you should remove the spy function.

Here is how you can modify the test:

it('should verify if onClick is triggered on button click and check the filter value', () => {
      component.myTitle = temp;
      fixture.detectChanges();

      let btn = fixture.debugElement.query(By.css('button'));
      btn.triggerEventHandler('click', null);

      fixture.whenStable().then(() => {
        expect(component.filter).toEqual("GokuSSj3");
      });

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

Navigate to a different component within Angular

Is there a way in Angular to scroll to a component using a button placed in another component? Below is the code snippet for the first component: <div id='banner' class="col-5 offset-1 d-flex justify-content-center align-items-cen ...

Adding a fresh attribute to MongoDB using push model

I wrote a basic script that calculates the number of documents for a specific user and assigns it to externalUser.totalIcons. However, when I try to execute it, the model is not saved and the new property is not added to the database. My question is: wher ...

Custom type declaration file in Typescript fails to function properly

I have searched through countless solutions to a similar issue, but none seem to work for me. I am attempting to utilize an npm package that lacks TypeScript type definitions, so I decided to create my own .d.ts file. However, every time I try, I encounter ...

Accessing nested objects within an array using lodash in typescript

After analyzing the structure of my data, I found it to be in this format: {property: ["a","b"], value : "somevalue" , comparison : "somecomparison"} I am looking for a way to transform it into a nested object like so: { "properties": { "a": { ...

What is the reason that setState functions properly when parsing each key separately, but fails when passed as an object?

Currently, I am delving into the world of React and TypeScript, but I have encountered a problem when trying to pass an object with a specific type in order to update the state. For some reason, the state remains unchanged. My approach involves using the ...

The function has been called but it did not return a

It seems that there is confusion surrounding the .toHaveBeenCalled() Matcher in Jasmine. While it should return a Promise that resolves when the function has been called, some users are experiencing it returning undefined instead. For example: it('sh ...

Having trouble deleting JavaScript object properties within a loop?

Struggling to comprehend the behavior of this particular piece of javascript code. const devices = searchResult.results.forEach(device => { const temp = Object.keys(device.fields); for(var property in temp) { if(device.fields.hasOwnPro ...

Transforming the string attribute of an object within a JavaScript array through mapping

Here is an array of objects: { "attr1": 123, "attr2": "a.end", }, { "attr1": 123, "attr2": "b.start", } The task is to remove the first part of the attr2 string up to and including the '.& ...

Inject the data within Observable<Object> into Observable<Array>

I'm faced with a situation where I have two distinct API endpoints. One endpoint returns a single Card object, while the other endpoint returns an Array of Card objects. My goal is to retrieve the first Card from the single Card endpoint and place it ...

Ensure the information remains secure within the Ionic provider

In my Ionic 3 project, I am sending an API request and displaying the response on a page called Home.ts by using a Provider. I want to ensure that the data remains in the provider after the initial request so that all pages utilizing this Provider can acce ...

Contrasting the utilization of `typeof` with a constant and `enum` in TypeScript

Can you explain the distinction between using typeof with a constant and an enum in TypeScript? For example: const TYPE_A = 'a' const TYPE_B = 'b' type MyType = | typeof TYPE_A | typeof TYPE_B type Result = { name: string type ...

Setting up Datatable in Angular 2+ without relying on jQuery

I need assistance with initializing a datatable for a table that has a unique id. Can you provide guidance on the syntax to achieve this? Here is an example of my table structure: <table id="myDataTable"> <thead> <tr> ...

What is the best way to incorporate a WYSIWYG Text Area into a TypeScript/Angular2/Bootstrap project?

Does anyone know of a WYSIWYG text editor for TypeScript that is free to use? I've been looking tirelessly but haven't found one that meets my needs. Any recommendations or links would be greatly appreciated. Thank you in advance! ...

Stream of information that triggers a specific action based on a specified condition

I'm dealing with an observable stream where I need to make two calls after retrieving the initial object using two id's found within the object. One of these id's, siteId, is optional and may or may not be present. If it is present, I need t ...

Exploring the functionality of surveyjs in conjunction with react and typescript

Does anyone have any code samples showcasing how to integrate Surveyjs with React and TypeScript? I attempted to import it into my project and utilized the code provided in this resource. https://stackblitz.com/edit/surveyjs-react-stackoverflow45544026 H ...

The presence of v-if does not depend on the model value to toggle the element

I have a scenario where I want to hide the dropdown menu for US states if a different country other than the US is selected. The code snippet I am using to achieve this functionality is shown below: <b-row v-for="demo in demographics" :key=&qu ...

Can you please provide a step-by-step guide for using socket.io with TypeScript and webpack, after installing it

Currently, I am experimenting with TypeScript in conjunction with node.js, socket.io, and webpack. To facilitate this setup, I have configured the webpack.config.js, tsconfig.json, and tsd.json files. Additionally, I acquired the typings file for socket.i ...

Searching function in material-table does not work properly with pipe symbol

Within my data table, I utilize the @pipe to display name instead of position in the position row... The name is sourced from a separate JSON file... <ng-container matColumnDef="position"> <mat-header-cell *matHeaderCellDef> No. </ma ...

Having trouble with your Typescript *.ts files?

Having trouble understanding why the command tsc *.ts isn't functioning correctly. The error message TS6053: File '*.ts' not found keeps appearing. Any suggestions on how to compile all the .ts files within a directory? Thank you! ...

Intellisense missing in VSCode for Angular and typings

Attempting to start a new project using Angular 1.5.5 and looking to incorporate TypeScript into my coding process within Visual Studio Code. I have included the necessary typings for Angular in my project: typings install angular --save --ambient I&ap ...