简体   繁体   中英

Close ngx-bootstrap modal after unit tests

Since I've enabled the css style in the unit tests of my Angular app, every time a component which shows a modal from ngx-bootstrap , it remains in the browser even after that specific component's unit tests have finished to run.

This makes hard to visually check the execution of the other tests and the test results:

在此处输入图片说明

UPDATE : code updated for ngx-bootstrap 6+, see below for older versions

The solution is to make sure the modals are hidden after each test that runs pieces of code that may show modals:

import { BsModalService } from 'ngx-bootstrap';

// test definitions ...

afterEach(() => {
  const modalService: BsModalService = TestBed.get(BsModalService);
  modalService.hide();
});

this technique is using the hide() method from the BsModalService .

I've found it useful to have a utility function that I can reuse in my tests:

export function closeModalsAfterEach() {
  afterEach(() => {
    const modalService: BsModalService = TestBed.get(BsModalService);
    modalService.hide();
  });
}

Old code (for versions before ngx-bootstrap 6)

Old working solution until ngx-bootstrap 5

import { BsModalService } from 'ngx-bootstrap';

// test definitions ...

afterEach(() => {
  const modalService: BsModalService = TestBed.get(BsModalService);
  modalService.hide(1);
});

export function closeModalsAfterEach(upToLevel: number = 1) {
  afterEach(() => {
    const modalService: BsModalService = TestBed.get(BsModalService);

    for (let level = 1; level <= upToLevel; level++) {
      modalService.hide(level);
    }
  });
}

you can remove it from the DOM

afterEach(() => {
  // const modalService: BsModalService = TestBed.get(BsModalService);
  // modalService.hide(1);
  const htmlCollection = document.getElementsByTagName('modal-container');
  if (htmlCollection.length > 0 && htmlCollection[0] != null)
    htmlCollection[0].remove();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM