UPDATE: code has been revised for ngx-bootstrap 6+ compatibility. Refer to the latest version below:
To ensure modals are hidden after running tests that may display modals, implement the following solution:
import { BsModalService } from 'ngx-bootstrap';
// define your tests...
afterEach(() => {
const modalService: BsModalService = TestBed.inject(BsModalService);
modalService.hide();
});
This approach utilizes the hide() method from the BsModalService.
A handy utility function that can be utilized across tests can be created for closing modals after each test:
export function closeModalsAfterEach() {
afterEach(() => {
const modalService: BsModalService = TestBed.inject(BsModalService);
modalService.hide();
});
}
Previous code (applicable for versions prior to ngx-bootstrap 6)
Previously functional solution for ngx-bootstrap versions up to 5
import { BsModalService } from 'ngx-bootstrap';
// define your tests...
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);
}
});
}