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.inject(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.inject(BsModalService);
modalService.hide();
});
}
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);
}
});
}