ngx-bootstrap modal is not being hidden when tested

In my Angular application, I am working on writing integration tests for a component that includes an ngx-bootstrap modal.

Within these integration tests, the component features a button that triggers a modal to appear. Within the modal, there is a "Save" button that is clicked during the testing process.

When the "Save" button is clicked, it calls a method: (click)=onSave() and this is the structure of the Modal Component:

constructor(
  protected bsModalRef: BsModalRef,
) {}


onSave() {
  // perform certain tasks (NOTE: this part is executed during testing)
  this.bsModalRef.hide();
}

Although the logic within the onSave() method is executed correctly, the modal does not disappear as expected during the test runs.

Strangely, manually clicking the button after the test is done running hides the modal properly.

Despite the fact that the button properly registers the click and triggers the onSave() method during the tests, the modal fails to disappear.

It is important to note that there are no spies used in this scenario, and in order to maintain the integrity of the integration test, I would like to avoid mocking the hide() method. Instead, I aim to resolve the issue to ensure that the modal hides during the test run and verify that it disappears along with the other outcomes of my custom onSave() method.

Answer №1

Could you consider using this alternative approach in your clickElement function within the test utilities file "page-object.ts"

Original Code:

clickElement(element: HTMLElement): void {
    element.click();
    this.fixture.detectChanges();
  }

Updated Code:

clickElement(element: HTMLElement): void {
    element.dispatchEvent(new MouseEvent('click'));
    this.fixture.detectChanges();
  }

Click here for an example of fakeAsync & tick() test

Answer №2

Make sure to store the modal reference in this.modalRef when displaying it.

constructor(private modalService: BsModalService) {}

ngOnInit() {
    this.modalRef = this.modalService.show(this.template, 
    { class: 'modal-md' });
}

save(){
     if (this.modalRef) {
        this.modalRef.hide();
     }
}

Answer №3

I encountered a similar issue and solved it by initially simulating setTimeout with

jasmine.clock().install()

Next, execute the following:

this.modalService.hide(this.modalRef.id) 

Subsequently, execute (if animated is set to true in the options, use 300 instead of 1)

jasmine.clock().tick(1)

conclude with:

jasmine.clock().uninstall()

Unfortunately, even after trying this.modalRef.hide(), it still does not function as intended. :(

Answer №4

To troubleshoot any issues with your component, make sure to inspect your browser console for any exceptions. I encountered a situation where I had a "throw error" code snippet within an unused OnInit method.

ngOnInit(): void {
    throw new Error("Method not implemented."); // <-- This is causing the problem
}

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

Issue with setting values in Angular2 when using IE 11 and shims included

First off, I want to clarify that I have indeed added the shims in my index.html file. <script src="node_modules/es6-shim/es6-shim.min.js"></script> <script src="node_modules/systemjs/dist/system-polyfills.js"></script> <script ...

When adjusting the window size with the <ion-split-pane>, both the menu and router outlet disappear

When I have two ion menus and one main content (router outlet) and resize the page or switch to mobile view, the page appears blank as if the content is missing. Here is the code: <ion-app> <ion-split-pane> <ion-menu side="start" me ...

Transform an Array into a String using Angular

Is there a more efficient way to extract all the state names from the array (testArray) and convert them to strings ('Arizona','Alaska','Florida','Hawaii','Gujarat','Goa','Punjab'...)? ...

"Put Jest to the test by running it with the Express

Currently, I am in the process of learning how to build an API with TypeScript and experimenting with testing it using the Jest framework. When utilizing a basic Express application like app = express() supertest(app) everything works smoothly. However, ...

What is the best way to integrate Circles into a line chart using the "d3.js" library?

I am encountering an issue with the placement of circles in a line chart created using d3.js. The circles are not appearing at the correct position on the chart. How can I troubleshoot and resolve this problem? My development environment is Angular, and t ...

Tips for sorting through and minimizing data based on the most recent date

info = { start: 1, data: [ { name: 'Maria', date: '2020-02-15 }, { name: 'Paula', date: '2020-06-10 }, { name: 'Eva', date: '2020-12-05 }, { name: 'Sophia', date ...

How can I combine multiple styles using Material-UI themes in TypeScript?

There are two different styles implementations in my code. The first one is located in global.ts: const globalStyles = (theme: Theme) => { return { g: { marginRight: theme.spacing(40), }, } } export const mergedStyle = (params: any) ...

Discover how TypeScript's strictNullChecks feature can help you identify null values with ease in your functions

Since Javascript often requires me to check if a value is `!= null && != ''`, I decided to create a function that checks for empty values: const isEmpty = (variable: any, allowEmptyString?: boolean): boolean => { return variable == null | ...

It seems that there is an issue with Ionic v4 and Angular when trying to retrieve the inner text of ion-slide elements in loop

I have a set of statuses displayed in <ion-slide> using the *ngFor directive to loop through a specified array: status: string[] = [ 'Active', 'Inactive', 'Ended' ]; @ViewChild('slideWithNav') slides: Io ...

Converting an image file from the local directory to base64 encoding in an Angular application

Can someone help me convert a locally stored image named xyz.JPEG from the folder assets/img to base64 in Angular 8? I have attempted using FileReader and btoa, but it has not been successful. var reader = new FileReader(); var binaryString = reader.rea ...

Modifying column array properties using jsstore

I am working with a jsstore table called tblInvoice const tblInvoice: ITable = { name: "invoice", columns: { // Here "Id" is name of column id: { autoIncrement: true, primaryKey: true, notNull: false }, branchId: { ...

Exploring the most effective strategies for creating a brand-new type in TypeScript?

In the execution environment I'm working with, there are several global constants that represent different directions: TOP = 1 TOP_RIGHT = 2 RIGHT = 3 BOTTOM_RIGHT = 4 BOTTOM = 5 BOTTOM_LEFT = 6 LEFT = 7 TOP_LEFT = 8 These constants are not just ran ...

What is the proper way to define a generic function that accepts a Union type as an argument?

I am dealing with various types and their unions. Here is the code snippet: type A = { name: string } type B = { work: boolean } type AB = A[] | B[] const func = (): AB => { return [{ name: 'ww' }] } const data = ...

Is there a method to enable the acceptance of both dots and commas as decimal markers in input fields?

Hey there! I have a question for you. Is there a way to allow users to input both commas and dots as decimal markers, but still display the value with dots and remove thousand separators? For example, when a user inputs "123456,78", they should see "123 ...

Style the date using moment

All languages had a question like this except for JavaScript. I am trying to determine, based on the variable "day," whether it represents today, tomorrow, or any other day. ...

Capturing the httpClient response within a service using rxjs

My application has a LoginComponent which includes a form for user credentials, and a LoginService responsible for making API calls using an httpClient. In my services, I usually return the call so that I can subscribe to it within my component as needed. ...

How can I utilize npm with the original source code instead of minified or bundled code?

I am looking to access npm and JavaScript (or TypeScript) 3rd party libraries directly from the source code. Similar to how I can make changes in Python libraries by going into their source code, I want to have the same capability with my JavaScript depen ...

The functionality of the Request interface appears to be malfunctioning

Hey there, I'm currently working on building an API using Express and TypeScript. My goal is to extend the Request object to include a user property. I've done some research on Google and found several posts on StackOverflow that explain how to d ...

Ways to implement JavaScript code in Angular 7 application

I am attempting to create a collapsible navigation bar using MaterializeCSS for mobile screens and I plan to incorporate JavaScript code into it. Can you advise where I should place this JavaScript code? Below is the snippet of code that I intend to inclu ...

Is there a way to modify the style when a different rarity is selected in Next.JS?

Is there a way to change the style depending on the rarity selected? I am currently developing a game that assigns a random rarity upon website loading, and I am looking to customize the color of each rarity. Here is how it appears at the moment: https:/ ...