Unit testing in Angular 4 with Jasmine Spy: The expectation was for 'New text' but received undefined

I have a simple function in my app.component.ts that is meant to modify a parameter, and I am trying to test this function using a spy. However, for some reason, my changeText function always returns undefined. Can you help me identify what I might be doing wrong?

Here is the code snippet from AppComponent.ts:

export class AppComponent {
    text = "My text";

    changeText = function () {
        this.text = "New text";
        return this.text;
    }
}

And here is the testing code from AppComponent.spec.ts:

describe("Testing with Spies", function () {  
      it("should successfully alter the text", function () {
      const fixture = TestBed.createComponent(AppComponent);
      const app = this.fixture.debugElement.componentInstance;

      spyOn(app, 'changeText');

      expect(app.text).toBe("My text");
      expect(app.changeText()).toBe("New text");          //This test fails
      expect(app.changeText).toHaveBeenCalledTimes(1);
  });
});

Answer №1

Consider implementing the following modifications if this is still applicable

Replace the following:

expect(app.changeText()).toBe("New text");
expect(app.changeText).toHaveBeenCalledTimes(1);

with:

app.changeText();
expect(app.text).toBe("New text");
expect(app.changeText).toHaveBeenCalled();

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 in React Router when using TypeScript

Encountering errors while trying to set up router with React and TypeScript. https://i.sstatic.net/muSZU.png I have already attempted to install npm install @types/history However, the issue persists. Your assistance would be greatly appreciated. Thank y ...

JavaScript for Office Spreadsheet Titles

I'm having trouble fetching the names of sheets from an external Excel file, as I keep getting an empty array. async function retrieveSheetNames() { const fileInput = <HTMLInputElement>document.getElementById("file"); const fileReader ...

Are you interested in verifying the user's login status on the website using a Chrome extension?

My latest project involves creating a chrome extension using angular for a PHP website. Currently, the extension is working smoothly. It features a button that I would like to have the ability to enable or disable based on whether the user is logged in o ...

Validation of time input using Angular Material within a ReactiveForm

Currently immersed in Angular 17 along with Material theme, I find myself faced with a scenario involving Reactive Forms housing two time-input fields. The array [minHour, maxHour] should represent a range of Hours, let's say [09:00 , 13:00]. HTML [ ...

Retrieving a list of actions triggered: Redux

In my Angular project, I am utilizing Redux to manage state and handle API calls. While exploring the redux devtools, I discovered a comprehensive list of executed actions. Is there a method to access a similar list of actions triggered within my angular a ...

Is it possible to deactivate input elements within a TypeScript file?

Is it possible to disable an HTML input element using a condition specified in a TS file? ...

Analyzing bundle files with Angular CLI output

Currently, I am utilizing Angular CLI to develop a production app by using the --prod switch. The resulting bundle is generated in the dist directory. Is there a method to determine which classes and functions have been included in the final bundle after ...

What could be the reason for my button not activating my JavaScript function?

I am encountering an issue with my form-validation sample. When I click the submit button, it should display an alert message but it is not working as expected. Here is a link to my sample: sample link I would greatly appreciate any assistance in res ...

Struggle between Angular and fundamental CSS principles

Upon following the steps below, I aim to achieve my desired grids: How to set auto-margin boxes in flexible-width design using CSS? The solution provided is effective when implemented outside of Angular. However, when inserted inside an Angular component ...

I am looking to conceal the y-axis labels and tooltip within the react chart

I am currently working with react-chart-2. I have a line graph that displays a tooltip when hovered over, but I would like to hide this tooltip feature. Additionally, I want to remove the numbers 0, 0.1, 0.2 up to 1 on the left side (y-axis) of the gra ...

Cannot perform table inserts or creates with NestJS Sequelize functionality

I am currently in the process of setting up a small web server with a MySQL database. To achieve this, I am utilizing NestJs along with Sequelize. However, as I am still in the learning phase, I seem to be encountering an error: Within my database, I have ...

Add up values from a reducer using two distinct actions

I have implemented ngrx-store in my project and created a reducer that handles two different actions. Each action contains the number of task count as payload. Now, I want to sum up the numbers from both actions when they are emitted. When I dispatch thes ...

Unit testing component in Ionic 2 with Ionic's specific markup and elements

Within my Angular 2 component for an Ionic 2 app, I utilize Ionic's markup as shown below: <ion-card> <h3>{{ rawcontent.name }}</h3> <p *ngIf="rawcontent.description">{{ rawcontent.description }}</p> </ion-car ...

Encountering an issue with the date pipe in Angular that prevents

I'm trying to incorporate a date pipe in my AngularJS and Firebase project to display the creation date of a post. However, I am facing an issue where the date does not appear when testing it. Below is my create Post function: createPost() { con ...

Executing the ngIf directive in Angular 2 when a function or click event occurs

Is there a way to display an element only when a specific function is executed or a particular click event occurs? Here's the html code snippet I'm currently working with: <sebm-google-map [latitude]="lat" [longitude]="lng" [zoom]="zoom" [map ...

Identifying whether a particular area is represented in a geographic map array presents a significant challenge

Having an issue with typescript currently. I have a variable that contains different string entries representing x, y positions. The entries are as follows: ["3,3","3,4","3,5","2,3","2,4","2,5","-1,-2","-2,- 2","-2,-1"] My goal is to determine if this land ...

Testing a reusable component in Angular using unit testing techniques

Currently, I am creating a test for an AppleComponent which has the following type: <T,U extends BananaComponent<T>>. This component also contains BananaComponent<T>. Target Component export class AppleComponent<T,U extends BananaCom ...

Angular's Spanning Powers

How can I make a button call different methods when "Select" or "Change" is clicked? <button type="button" class="btn btn-default" *ngIf="!edit" class="btn btn-default"> <span *ngIf="isNullOrUndefined(class?.classForeignId)">Select</spa ...

The Angular project seems to be experiencing technical difficulties following a recent update and is

Recently, I made the transition from Angular 6 to 8 and encountered two warnings during the project build process that I can't seem to resolve. Despite searching online for solutions, nothing has worked so far. Any help would be greatly appreciated. ...

`Mapping child routes in Angular using basic components`

I am encountering an issue with Angular 8 routes. The problem lies in the child routes not functioning properly. Here are my defined routes: const routes: Routes = [ { path: 'admin', component: MainComponent, children: [ { path: &apo ...