Angular Testing: Discovering the best practices for asserting expectations post function execution

I'm currently facing a challenge while unit testing my Angular application. I need to make an HTTP call on a local file, but the expects of the test are getting called before and after the HTTP call, causing it to crash. How can I resolve this issue?

My current approach is to place the expects inside the .subscribe of the HTTP call:

fit('should fetch local file and process it', (done: DoneFn) => {
        let file: File;

        var blob: Blob;

        httpMockService.get('/assets/testFiles/testImage.png', { 
                      responseType: 'blob' }).subscribe((resp: any) => {
      
    blob = resp;
    file = new File([blob], 'logo.png', 
                     { type: 'image/png', lastModified: Date.now() });

    component.submitFile(file); <- gets called second

    expect(component.canBeProgressed).toEqual(true); <- gets called first
    expect(component.submitted).toEqual(false);

    done();

});

The problem lies in the fact that the expected values are incorrect because component.submitFile is being called after the expects. I attempted using a spy, but it didn't work. Can anyone provide assistance?

Edit: The submitFile() method includes a FileReader that loads the image and manipulates its pixels. I believe this may be causing the issue.

Answer №1

Testing doesn't always require fetching a file from assets. It is possible to simulate a file in your tests.

    it('should test functionality with a local file', () => {
          let blob = new Blob([""], { type: 'image/png' });
          blob["lastModifiedDate"] = Date.now()
          blob["name"] = "test.png";

          let mockFile = <File>blob;
   
         component.submitFile(mockFile);
    
         expect(component.canBeProgressed).toEqual(true); 
         expect(component.submited).toEqual(false);
    
    
    });

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

Getting the value returned by http.request in an app.get method using express.js

When attempting to deliver data from an API on another domain using app.get, I am able to write the data to the console successfully. However, the data is not showing up on the page ('~/restresults'). This is the current code I have: app.get(&a ...

Run JavaScript code whenever the table is modified

I have a dynamic table that loads data asynchronously, and I am looking for a way to trigger a function every time the content of the table changes - whether it's new data being added or modifications to existing data. Is there a method to achieve th ...

How can Angular hide a global component when a particular route is accessed?

Is it possible to hide a global component in Angular when a specific route is opened? For instance, consider the following code: app.component.html <app-header></app-header> <app-banner></app-banner> <!-- Global Component I w ...

Using Angular 2 to showcase icons in the navbar post authentication

The structure of my components is as follows: The app component contains a navigation bar and router outlet. The navigation bar includes a logo, generic links, and specific links that are only shown after user login and authentication. The router outlet de ...

Easiest Angular Carousel Solution

My goal is to create a basic Angular Carousel to enhance my understanding of Angular. While I have received helpful answers in the past, I am seeking further clarification to deepen my knowledge of Angular2+ and Typescript. Here's what I have so far: ...

SyntaxError: Unexpected token '<' in Angular 6

I have been working on an angular website project. Here is the package.json file for my production environment: "dependencies": { "@angular/animations": "^5.0.2", "@angular/cdk": "^5.1.0", "@angular/common": "^5.0.2", "@angular/compiler": ...

Steps for obtaining the current state array post re-ordering column in Angular datatables

I am facing an interesting scenario where I can successfully retrieve the current state of an array of columns using pure JS + jQuery, but unfortunately, the same approach does not seem to work in Angular 12! Despite going through the documentation for Ang ...

Discovering Child Elements in Angular 2 with @ViewChild and CSS Selectors

I'm looking to update the style of the second paragraph using either the nth-child() selector or by a specific class: import { Component, ViewChild } from '@angular/core'; @Component({ selector: 'my-app', template: ` <d ...

Upgrade from Angular 7 to the latest version, Angular 8

Here is the content of my package.json file: "@agm/core": "^1.1.0", "@angular/animations": "^8.2.14", "@angular/cdk": "^6.4.7", "@angular/common": "^8.0.0", "@angular/compiler": "^8.2.14", "@angular/core": "^8.2.14", "@angular/forms": "^8.2.14", "@angular ...

Is it possible to utilize ion-input's form validation while utilizing an HTML pattern for input?

I am working on validating an ion-input using a regex pattern in the HTML code. The purpose of this is to only allow numbers from 0 to 24 as input. Currently, this validation is functioning correctly and displays an error message if an incorrect number or ...

Angular - Detecting Scroll Events on Page Scrolling Only

I am currently working on implementing a "show more" feature and need to monitor the scroll event for this purpose. The code I am using is: window.addEventListener('scroll', this.scroll, true); Here is the scroll function: scroll = (event: any) ...

Creating a consolidated System.config mapping for @angular modules using a single .js file

Currently in the process of developing an Angular 2 application, with the specific requirement to consolidate all resulting Javascript files into a single .js file called output.js. Now, the challenge is to incorporate map configuration within System.conf ...

Guide on updating a property key in Firebase real-time database with Angular 7

Is it possible to modify the key of a property in my firebase database that I have been struggling with? ...

Exploring the conjunction of karma, jasmine, and angularJS: My personal journey into unit testing a

I am looking for a simple directive that will allow me to easily create a modal in AngularJS. The directive should take a template and generate a button that, when clicked, opens the modal with the template as its content. <script type="text/ng-templat ...

Creating and Injecting Singleton in Angular 2

I have a custom alert directive set up in my Angular app: import { Component } from 'angular2/core'; import { CORE_DIRECTIVES } from 'angular2/common'; import { Alert } from 'ng2-bootstrap/ng2-bootstrap'; @Component({ sele ...

Tips for displaying real-time data and potentially selecting alternative options from the dropdown menu

Is there a way to display the currently selected option from a dropdown list, and then have the rest of the options appear when the list is expanded? Currently, my dropdown list only shows the available elements that I can choose from. HTML: < ...

Is there a way to establish a connection between two excel entries using Angular?

In order to connect xlsx file records with their corresponding ids using angular, I am seeking a solution. To elaborate further: Let me provide an example for better understanding: Scenario 1 https://i.stack.imgur.com/25Uns.png Scenario 2 https://i ...

The error message "ng2-test-seed cannot be found - file or directory does not exist"

I've been attempting to work with an angular2 seed project, but I'm encountering some challenges. https://github.com/juliemr/ng2-test-seed When I run the command: npm run build I encounter the following error: cp: cannot stat ‘src/{index.h ...

Navigating with Angular router in a Bootstrap navigation bar

My link is not displaying as a tab (I'm using Bootstrap 4 and Angular 5). Instead, it shows up as just a plain link. This seems like it should be a simple issue, but this is my first time working with bootstrap... Thank you! <div> <nav cla ...

The issue with the Angular 5 HttpClient GET-Request not closing persists

Currently, I am utilizing an Http-GET request to fetch JSON data from my backend service. Service: public storedCategories: BehaviorSubject<Category[]> = new BehaviorSubject(null); constructor() { const subscription = this.http.get&l ...