--[[
	Temporarily mounts a Roact element in the DataModel so that it can be tested
	with Rhodium.

	Usage:

		local wasClicked = false

		local element = Roact.createElement("TextButton", {
			[Roact.Event.Activated] = function()
				wasClicked = true
			end
		})

		withMountedElement(element, function(button: TextButton)
			button = Rhodium.Element.new(button)
			button:click()
			expect(wasClicked).toBe(true)
		end)
]]


local CoreGui = game:GetService("CoreGui")

local ExperienceComponents = script:FindFirstAncestor("ExperienceComponents")

local Roact = require(ExperienceComponents.Parent.Roact)

local function withMountedElement<T>(element: any, test: (T) -> ())
	local screenGui = Instance.new("ScreenGui")
	screenGui.Name = "RhodiumScreenGui"
	screenGui.ZIndexBehavior = Enum.ZIndexBehavior.Sibling
	screenGui.Parent = CoreGui

	local handle
	local success, result = pcall(function()
		handle = Roact.mount(element, screenGui)
	end)

	if not success then
		screenGui:Destroy()
		error(result)
	end

	success, result = pcall(function()
		test(screenGui:FindFirstChildWhichIsA("GuiObject"))
	end)

	Roact.unmount(handle)
	screenGui:Destroy()

	if not success then
		error(result)
	end
end

return withMountedElement
