import { beforeEach, describe, expect, it, jest } from '@jest/globals'

const mockRender = jest.fn()
const mockCreateRoot = jest.fn(() => ({ render: mockRender }))

jest.mock('react-dom/client', () => ({
  createRoot: mockCreateRoot,
}))

jest.mock('./App', () => function MockApp() {
  return null
})

describe('main entrypoint', () => {
  beforeEach(() => {
    jest.resetModules()
    document.body.innerHTML = '<div id="root"></div>'
    mockCreateRoot.mockClear()
    mockRender.mockClear()
  })

  it('mounts the app into #root', async () => {
    await jest.isolateModulesAsync(async () => {
      await import('./main')
    })

    expect(mockCreateRoot).toHaveBeenCalled()
    expect(mockRender).toHaveBeenCalled()
  })

  it('fails fast when the root node is missing', async () => {
    document.body.innerHTML = ''

    await expect(
      jest.isolateModulesAsync(async () => {
        await import('./main')
      }),
    ).rejects.toThrow('Missing <div id="root"></div> in index.html')
  })
})
