Exploring Angular component testing through jasmine/karma and utilizing the spyOn method

I have been facing an issue while trying to test my component. Even though the component itself works perfectly, the test keeps generating error messages that I am unable to resolve.

Here is the snippet of code that I am attempting to test:

    export class AddressListComponent implements OnInit {

      paginate: PaginateInterface = new Paginate(Address);
      addresses: AddressInterface[] = [];

      constructor(
        private addressService: AddressService,
        private addressTypeService: AddressTypeService,
        private countryService: CountryService,
        private settlementService: SettlementService,
        private serviceNatureOfTheSite: NatureOfTheSitesService,
        private router: Router,
      ) {
      }

      ngOnInit() {
        if (!this.isBind ) {
          this.addressService.getAll().subscribe( (resolve: PaginateInterface) => {
            this.paginate = resolve;
            this.addresses = this.paginate.data;
          },
          error => {
            throw(error);
          });
        }
      }
    }

Below is the test script that seems to be causing issues:

    describe('AddressListComponent', () => {
      const httpClient = new HttpClient(null);
      let injector: Injector;
      let component: AddressListComponent;
      let service: AddressService;
      let settlementService: SettlementService;
      let countryService: CountryService;
      let addressTypeService: AddressTypeService;
      let natureOfTheSiteService: NatureOfTheSitesService;
      const datas = [
        {name: 'test 1'},
        {name: 'test 2'},
        {name: 'test 3'},
      ];
      const paginateData = new Paginate(Address, {
        data: datas,
      });

      beforeEach(() => {
        settlementService = new SettlementService(httpClient, injector);
        countryService = new CountryService(httpClient, injector);
        addressTypeService = new AddressTypeService(httpClient, injector);
        natureOfTheSiteService = new NatureOfTheSitesService(httpClient, injector);
        service = new AddressService(httpClient, injector, settlementService, countryService, addressTypeService, natureOfTheSiteService);
      });

      it('should set address property with the items returned from server', () => {
        spyOn(service, 'getAll').and.returnValue(of(paginateData));

        component = new AddressListComponent(service, addressTypeService, countryService, settlementService, natureOfTheSiteService, null);

        expect(component.addresses.length).toBe(datas.length);
      });
    });

The console displays the following error message:

    Chrome 79.0.3945 (Windows 10.0.0) AddressListComponent should set address property with the items returned from server FAILED
            Expected 0 to be 3.
                at UserContext.<anonymous> (http://localhost:9876/_karma_webpack_/src/app/components/address/address-list/address-list.component.spec.ts:49:40)
    Chrome 79.0.3945 (Windows 10.0.0): Executed 1 of 2 (1 FAILED) (0 secs / 0.137 secs)
    Chrome 79.0.3945 (Windows 10.0.0) AddressListComponent should set address property with the items returned from server FAILED
            Expected 0 to be 3.
                at UserContext.<anonymous> (http://localhost:9876/_karma_webpack_/src/app/components/address/address-list/adChrome 79.0.3945 (Windows 10.0.0): Executed 2 of 2 (1 FAILED) (0.146 secs / 0.138 secs)
    TOTAL: 1 FAILED, 1 SUCCESS
    TOTAL: 1 FAILED, 1 SUCCESS

I can confirm that the code functions correctly, so the issue appears to lie within the test. Any insights on what could be going wrong?

Answer №1

If you find that your component is not initialized properly in your test case, consider explicitly calling ngOnInit(). Here's an example:

 it('should set address property with the items returned from server', () => {
    spyOn(service, 'getAll').and.returnValue(of(paginateData));

    component = new AddressListComponent(service, addressTypeService, countryService, settlementService, natureOfTheSiteService, null);
    component.ngOnInit();
    expect(component.addresses.length).toBe(datas.length);
  });

If you're using TestBed to create your component and its dependencies, as recommended in the official documentation here, you can also use detectChanges method to initialize the component (which in turn calls ngOnInit).

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

Troubleshooting jQuery.ajax - Why won't it function properly?

I've been struggling to get the ajax service functioning properly. I tried a simple $.get("http://google.com"), but it didn't work. Additionally, this code snippet failed as well: <html> <head> <script src="https://aja ...

What is the best way to organize an array both alphabetically and by the length of its elements?

Imagine I am working with an array like this: ['a', 'c', 'bb', 'aaa', 'bbb', 'aa']. My goal is to sort it in the following order: aaa, aa, a, bbb, bb, c. this.array= this.array.sort((n1, n2) => ...

Storing POST Request Data in Express

I want to use a single API endpoint for both GET and POST requests. My goal is as follows: Send multiple POST requests to /api/users with data like: {'id': 2, is_valid: 'true'} Retrieve this data by fetching the same API URL later on ...

Strange occurrences with HTML image tags

I am facing an issue with my React project where I am using icons inside img tags. The icons appear too big, so I tried adjusting their width, but this is affecting the width of other elements as well. Here are some screenshots to illustrate: The icon wit ...

Steps for deactivating a textbox upon checkbox activation

When I try to implement the instructions from the textbook, I'm encountering an issue where clicking on the checkbox doesn't disable the textbox on my website. <form action="#"> Billing Address same as Shipping Address: <input ...

One approach could be utilizing either JavaScript object notation or jQuery code to establish class properties that are also classes in their own

Here is an example of what I currently have: var Class1=function(p1,p2){ //constructor code } Class1.prototype={ method:function(){...}, method:function(){...} } I am looking to make Class2 a part of Class1 so that I can do the following: inst ...

Sending arrays from HTML table rows to a JavaScript function

When developing a dynamic table using Javascript, I am able to add rows programmatically with the following function: function addrow(tableid) { var tablename = document.getElementById(tableid); var rows = tablename.rows.length; if (rows < ...

Unique option preservation on customized HTML select menus - Maintain original selection

Currently, I am attempting to replicate a custom HTML select based on the example provided by W3 Schools. You can view the demo through this link: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_custom_select The issue I am encountering is that ...

Tips for arranging elements in proper order following a rotation

Having trouble aligning rotated divs? Let's say we rotate .straight by 30deg, and now we want to find the new offset coordinates of its bottom right corner. This way, we can perfectly match up the bottom left corners of .curve with this new coordinate ...

Having issues with Cypress testing of Material-UI datepicker on Github actions

Encountering an unusual issue while running Cypress tests in a GitHub action environment. The MUI datepicker is stuck in readonly mode, preventing any input of dates (works fine in other setups). Error displayed by Cypress CypressError: Timed out retryin ...

I am currently working on creating a navigation bar for a webpage using the express framework and pug library. However, when I navigate to the demo page endpoint, the screen appears blank and nothing is displayed

//In the following JavaScript code, I am trying to implement basic routing navigation using express. However, when I try to insert HTML into the demo page, nothing appears on the browser screen. const path = require("path"); const app = ...

Does Firestore arrayunion offer any kind of callback function?

Hey there! I'm currently working on a voting system and I want to prevent the same user from voting multiple times on the same post. let db = firebase.firestore(); var postRef = db.collection("posts").doc(this.pid); postRef.update({ ...

"Encountering difficulty in retrieving information from $q and integrating it into the

I am facing an issue with binding data from an API to my scope using promises in AngularJS. Despite successfully retrieving the JSON data from the server, the $scope variable remains empty. Any assistance on this matter would be greatly appreciated. Thank ...

Upon implementing a catch-all express routing solution, the Fetch API calls are no longer successful. The error message received is "Unexpected token < in JSON at

While working on a React project, I encountered an issue outlined in this link: React-router urls don't work when refreshing or manually typing. To resolve this problem, I decided to implement the "Catch-All" solution recommended in that discussion. ...

Error: React unable to locate module './WebpackMissingModule'

Recently I started diving into React, and I'm encountering some difficulties trying to export components. Here is my current index.js file setup: import React from 'react'; import ReactDOM from 'react-dom'; import SearchBar from ...

React Hooks encountering issues with keydown/up events functionality

Currently, I am in the process of implementing arrow-based keyboard controls for a game that I have been developing. In order to stay updated with React, I decided to utilize function components and hooks. To showcase my progress, I have put together a dem ...

Issue: The module 'xdl' cannot be located while executing the command "npm start" in React Native

Recently, I delved into learning React Native through an online Udemy course. Everything was going smoothly until a few days back when I encountered an error message after running the simple "npm start" command. Despite trying various solutions like reinst ...

Automated pagination in Jquery running seamlessly

I have successfully created pagination using jQuery. Although the script is functioning properly, I now want it to automatically switch between different pages: <script> $(document).ready(function(){ $("#article_load_favourites").load("indexer_favo ...

Ignoring setTimeout() function within forEach() in Angular leads to issues

I am currently working on the frontend development of a Web Application using Angular. My task involves saving data from an array into a database by making repeated API calls until all the array data is processed. I implemented the use of setTimeout() in ...

Filter an object in Typescript and retrieve a single key

Managing a set of checkboxes is essential in assigning roles to new users. While it's possible to filter and retrieve only the checked checkboxes, extracting just the "name" key poses a challenge. The current method involves filtering with a for loop ...