Testing the selection of dropdown values in Angular2 using unit tests

I have a dropdown menu for selecting countries. It defaults to a pre-selected value, and when the user changes it, they are redirected to the corresponding country page.

However, I am facing an issue while trying to unit test the default value in the select box. The selectEl.nativeElement.value keeps returning an empty string ''. Does anyone have any insights on why this might be happening?

// locale-component.ts
import { Component } from '@angular/core';
import { cultures} from '../../../config/config';

@Component({
  selector: 'app-locale',
  templateUrl: './locale.component.html',
  styleUrls: ['./locale.component.scss']
})
export class LocaleComponent {

  cultures = cultures;

  constructor() {}

  onLocaleChange(locale) {
    const str = window.location.href.replace(new RegExp(`/${this.cultures.default}/`), `/${locale}/`);
    window.location.assign(str);
  }
}


// locale.component.spec.ts

beforeEach(() => {
  fixture = TestBed.createComponent(LocaleComponent);
  component = fixture.componentInstance;
  component.cultures = {
    default: 'en-ca',
    supported_cultures: [
      { "name": "United States", "code": "en-us" },
      { "name": "Canada (English)", "code": "en-ca" },
      { "name": "Canada (Français)", "code": "fr-ca" }
    ]
  }
  fixture.detectChanges();
});

it('should create', () => {
  expect(component).toBeTruthy();
});

it('should select the correct flag/locale by default', () => {
  fixture.detectChanges();
  const selectEl = fixture.debugElement.query(By.css('select'))
  console.log(selectEl)
  fixture.detectChanges();
  fixture.whenStable().then(() => {
    expect(selectEl.nativeElement.value).toEqual('en-ca');
  });
});


<!-- locale.component.html -->
<label class="locale locale--footer">
  <div class="locale__custom-select locale__custom-select__button locale__custom-select__ff-hack">
    <select [ngModel]="cultures.default" (ngModelChange)="onLocaleChange($event)">
      <option *ngFor="let locale of cultures.supported_cultures" [ngValue]="locale.code">{{locale.name}}</option>
    </select>
  </div>
</label>

Answer №1

"Executing detectChanges() within whenStable()" activates the dropdown menu.

fixture.whenStable().then(() => {
  fixture.detectChanges();
  expect(selectEl.nativeElement.value).toEqual('en-ca');
});

Answer №2

Give this a shot:

fixture.detectChanges();
const selectElement = fixture.debugElement.query(By.css('select'))
console.log(selectElement);
fixture.detectChanges();
fixture.whenStable();
expect(selectElement.nativeElement.value).toEqual('en-ca');

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

Comparing react-intl and react-i18next for internationalizing ReactJS applications

I am in the process of developing a multilanguage application using ReactJS. This application will require a custom dictionary for various languages, as well as automatic formatting for date/time, numbers, and currency. After researching, I have come acro ...

After downloading the quickstart (angularjs2) from angular.io, I encountered an error when trying to start npm

[email protected] typing start G:\quickstart\quickstart-master tsc && concurrently "tsc -w" "lite-server" [1] 'lite-server' is not recognized as a valid command, [1] executable program or batch file. [1] lite-serve ...

Setting the select option in AngularJS with predefined options can be easily achieved with

I am encountering an issue with a select element that has predefined options. Even though the select element is using ng-model, when the model is set to one of the option values, it fails to be selected. Below is the snippet of HTML code: <select clas ...

Testing Vue.js Components with JEST

Encountering an unusual issue while attempting to run a JEST unit test. import { shallowMount } from '@vue/test-utils' import communicationPreferences from '@/pages/account/communication-preferences' describe('Communication Prefer ...

What is the best way to retrieve multiple variables using Express.js on Node.js?

Trying to fetch Form data from an HTML page to a Node Js server. The HTML file is named index.html <body> <nav> <ul> <li> <a href="#" class="button add">Add Product</a> <div class="dialog" style="displ ...

How can cookies be managed with JavaScript, Express.js, or Node.js?

Could anyone advise on the optimal approach for managing cookies - through Express.js, Node.js, or client-side JavaScript/jQuery? I'm feeling a bit uncertain about security implications. Your assistance and insights are greatly appreciated. ...

How can we align the top edge of a div to the center of a circle within a separate div in a responsive manner?

I want to create 2 stacked divs: the first div contains a circular image, and the second div contains text. I want the second div to always cover half of the circle, with its upper edge positioned at the center point of the circle. This is my code: .cov ...

Problem with OnClick function in Firefox

I have implemented the following code in an external JavaScript file: $( document ).ready(function() { var elem='<img class="imgload" src="/common/images/spinLoader/transperent.png">'; $('.imgchange').append(elem); }); $(func ...

Can you explain the distinction between bodyparser.urlencoded and bodyparser.json?

I'm a bit confused about the use of bodyparser. Why is it necessary when we can simply use json.stringify (to convert an object to a string) and json.parse (to convert JSON to an object)? Is it because by using app.use() with bodyparser, the middlewa ...

Adjusting the size of the snap increments

When using gridstack, I have the ability to resize my widgets. However, I've noticed that when dragging on the widgets' handles, they snap to specific sizes, which seems to be a fixed amount. If I wanted to set the widget's size to something ...

Accessing class functions in Angular 2 and Ionic

I'm currently using Ionic with Angular 2 to develop an app. However, I'm facing an issue with the code below as I am unable to access the function leaveGroup(group) within the Dialog promise. leaveGroupTapped(event, group) { this.dialogs.con ...

Could you provide the parameters for the next() function in Express?

Working with Express.js to build an API has been a game-changer for me. I've learned how to utilize middlewares, handle requests and responses, navigate through different middleware functions... But there's one thing that keeps boggling my mind, ...

Looking to showcase a loading gif inside a popover before swapping it out with ajax-generated content

My goal is to populate a popover with content using ajax requests. Here's the setup: $('.openMessagePopover').popover({ html: true, content: function() { $threadId = $(this).data('id'); return getContent($threadId) ...

Storing information within a global variable array or exploring alternative methods

I am currently working on a project in electron / node.js and need assistance with the following tasks: Importing data from excel/csv files Visualizing the data using d3.js Cleaning the data by removing duplicates, etc. Using the data for calcu ...

JQuery displays 'undefined' on checkbox loaded via Ajax

Currently, I am utilizing a checkbox to activate my select Option tag. The select option tag and checkbox are both loaded via ajax. While the select option works perfectly, the checkbox displays as undefined. However, it functions properly in enabling my d ...

What is causing a 500 internal error in Django when using Ajax?

Can someone help me troubleshoot why I keep receiving a 500 internal error when trying to execute an Ajax function? I attempted to send the response from view.py to the Ajax function in two different ways: using JsonResponse (see 'else' section i ...

Incorporate tinyMCE into a colorbox module

Currently, I am facing an issue on my website where there are textareas with tinymce. While I can view all the textareas correctly, when trying to open colorbox within a textarea, it does not inherit the tinymce properties. The code snippet used to open co ...

What is the best way to toggle the visibility of a side navigation panel using AngularJS?

For my project, I utilized ng-include to insert HTML content. Within the included HTML, there is a side navigation panel that I only want to display in one specific HTML file and not in another. How can I achieve this? This is what I included: <div ng ...

Is there a way to get rid of the tiny black line beside the Instagram icon?

Here is the display on my website This is the code that was used I am struggling to identify the source of the small black "-" line next to the Instagram icon logo. ...

jQuery dynamic id selection

I'm facing a challenge with dynamically generated forms that have dynamically generated IDs and potentially classes. Although the forms are identical, they each have a unique ID at the end. How can I target and manipulate each set of inputs individua ...