import { fireEvent } from "@testing-library/react" ; import { expect } from "chai" ; import { ITwinLocalization } from "@itwin/core-i18n" ; import { UiCore } from "../core-react/UiCore" ; internal export class TestUtils { private static _i18n ? : ITwinLocalization ; private static _uiCoreInitialized = false ; public static get i18n ( ) : ITwinLocalization { return TestUtils . _i18n ! ; } public static async initializeUiCore ( ) { if ( ! TestUtils . _uiCoreInitialized ) { TestUtils . _i18n = new ITwinLocalization ( ) ; await TestUtils . _i18n . initialize ( [ "IModelJs" ] ) ; await UiCore . initialize ( TestUtils . i18n ) ; TestUtils . _uiCoreInitialized = true ; } } public static terminateUiCore ( ) { UiCore . terminate ( ) ; TestUtils . _uiCoreInitialized = false ; } public static createBubbledEvent ( type , props = { } ) { const event = new Event ( type , { bubbles : true } ) ; Object . assign ( event , props ) ; return event ; } /** Waits until all async operations finish */ public static async flushAsyncOperations ( ) { return new Promise ( ( resolve ) => setTimeout ( resolve ) ) ; } } internal export const storageMock = ( ) => { const storage = { } ; return { setItem : ( key , value ) => { storage [ key ] = value || "" ; } , getItem : ( key ) => { return key in storage ? storage [ key ] : null ; } , removeItem : ( key ) => { delete storage [ key ] ; } , get length ( ) { return Object . keys ( storage ) . length ; } , key : ( i ) => { const keys = Object . keys ( storage ) ; return keys [ i ] || null ; } } ; } ; /**
 * Select component change value using text of menu item to find item
 */ export const selectChangeValueByText = ( select , label , onError ? ) : void => { fireEvent . click ( select . querySelector ( ".iui-select-button" ) as HTMLElement ) ; const menu = select . querySelector ( ".iui-menu" ) as HTMLUListElement ; if ( ! menu ) onError && onError ( `Couldn't find menu` ) ; expect ( menu ) . to . exist ; const menuItems = menu . querySelectorAll ( "li span.iui-content" ) ; if ( menuItems . length <= 0 ) onError && onError ( "Couldn't find any menu items" ) ; expect ( menuItems . length ) . to . be . greaterThan ( 0 ) ; const menuItem = [ ... menuItems ] . find ( ( span ) => span . textContent === label ) ; if ( ! menuItem ) onError && onError ( `Couldn't find menu item with '${ label }' label` ) ; expect ( menuItem ) . to . not . be . undefined ; fireEvent . click ( menuItem ! ) ; } ; /** Handle an error when attempting to get an element */ export function handleError ( msg ) { console . log ( msg ) ; } /** Stubs scrollIntoView. */ export function stubScrollIntoView ( ) { const originalScrollIntoView = window . HTMLElement . prototype . scrollIntoView ; const scrollIntoViewMock = function ( ) { } ; beforeEach ( ( ) => { window . HTMLElement . prototype . scrollIntoView = scrollIntoViewMock ; } ) ; afterEach ( ( ) => { window . HTMLElement . prototype . scrollIntoView = originalScrollIntoView ; } ) ; } export default TestUtils ;