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

Utilize an Ajax dropdown menu that allows users to enter search criteria, such as location or city

Looking for a way to display weather information based on a selected city? Check out this code snippet that uses Yahoo API to pull data and show weather details. Here's the code: <HTML> <HEAD> <TITLE>Find Weather in major cities ar ...

Adding two input values using jQuery

Here is the function compute() that I am working with: function compute() { if ($('input[name=type]:checked').val() != undefined) { var a = $('input[name=service_price]').val(); var b = $('input[name=modem_pric ...

Encountered an unanticipated symbol at column 2 while using the Angular Google Recaptcha

I have integrated the Angular Google Recaptcha directive into my application from https://github.com/VividCortex/angular-recaptcha. However, upon running my application, I encountered an error stating that I am using my public key instead of my private key ...

What is preventing type-graphql from automatically determining the string type of a class property?

I have a custom class named Foo with a property called bar that is of type string. class Foo { bar: string } When I use an Arg (from the library type-graphql) without explicitly specifying the type and set the argument type to string, everything works ...

What is the method for utilizing the onmouseover function to emphasize a specific part of an SVG graphic?

I am attempting to create an interactive SVG map of Europe. Each country is represented by a path element, and I want the opacity of a country to change to 0.5 when it is hovered over. Despite trying to define a JavaScript function for this purpose, noth ...

Troubleshooting problem with transmitting data using the b4j jQuery WebSocket library

I'm seeking guidance on the process of sending data through a custom library that connects to a Java server operating as a WebSocket server. The code I'm using for successful connection is: <script src="https://ajax.googleapis.com/ajax/libs/ ...

Step-by-step guide on uploading an image file using Nextjs

I am attempting to achieve the following: Upload an image file to a Next.js application Process it using cjwbw/real-esrgan:d0ee3d708c9b911f122a4ad90046c5d26a0293b99476d697f6bb7f2e251ce2d4 Retrieve the enhanced version of the image Is there anyone who can ...

Utilizing OverlappingMarkerSpidifier in conjunction with sebm-angular2-google-map

I'm currently integrating OverlappingMarkerSpidifier using SebM Angular 2 Google Maps on angular2 2.0.0. After successfully loading the google maps API with the GoogleMapsAPIWrapper imported from the sebm module, I am running into an issue when execu ...

Issue with RouterLink functionality in Angular 6

While following a Brad Traversy tutorial on coding, I implemented the instructions exactly as given. Below is my 'app.module.ts' file. import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/c ...

Showing Arrays in Angular on HTML Page

I have created an array that stores multiple arrays with 3 indexes each. An example of the structure looks like this: (3) [Array(3), Array(3), Array(3)] 0: (3) [199.4, 10.5, 19] 1: (3) [47.2, 2.1, 23] 2: (3) [133.6, 5.3, 25] In my HTML, I want to display ...

Using React Native with TypeScript to Select the Parent and Child Checkboxes within a FlatList

My objective is to ensure that when a user selects a checkbox for one of the parent items ('Non Veg Biryanis', 'Pizzas', 'Drinks', 'Desserts') in the flatlist, all corresponding child items should also be selected au ...

Enhance the visual appeal of incoming data using Angular Material's dynamic styling feature

Is it possible to enhance the text with some CSS styling to make each item stand out like in this example: https://i.stack.imgur.com/kSyZE.png I prefer not to include a cross button or provide users with the option to add tags. The data is coming from a R ...

Override existing Keywords (change false to true)

Are there any ways to overwrite reserved words? It's not something I would typically consider, but it has sparked my curiosity. Is it feasible to set false = true in JavaScript? I've come across instances on different websites where individuals ...

Insert a new class within the container div

I am looking to insert a 'disabled' class within a parent div named 'anchorxx' The disabled class div can be located anywhere within the anchorXX divs Is it achievable using jquery? I am unsure how to approach this task. Appreciate y ...

Angular: Struggling with Parent Component not recognizing changes in Child Component

Currently, I am facing an issue with my shopping cart functionality. When the website first loads and a user does not have a saved shopping cart, they need to click "add to cart" before one is created. The problem lies in the fact that my app.component doe ...

Instructions for returning a function from within another function and then displaying it upon return

My current state: constructor(props) { super(props); this.state = { temperatureConversion: '', Here is the function I'm using: handleChange = async (value) => { this.setState({ value }); await Axios.ge ...

The transformation from className to class attribute does not occur for custom elements in JSX

I recently encountered an issue with one of my React components where the "className" attribute was being converted to "classname" in the resulting HTML, instead of the expected "class" attribute. The component had a custom element definition as follows: ...

JavaScript - Modify input character prior to appending it to the text area

I am working on creating a virtual keyboard using jQuery. Whenever I press 'a' in the textarea, I want it to display 'z' instead. In my investigation of typing a letter in the textarea, I discovered the following sequence: keyDown ev ...

How to style a div for printing using CSS

Currently, I am working on a project that has already been completed but now requires some enhancements. To give you an overview, the project includes a search functionality that displays additional details upon clicking on the displayed name in the result ...

Need inspiration for testing web content with Protractor?

Exploring new possibilities for testing web content with Protractor. Any fresh ideas on what else can be tested? So far, I've checked links to ensure they redirect correctly. I've also verified text color and decoration changes when hovering ove ...