import { createElement, render } from 'preact';
import { setupScratch, teardown } from '../../../test/_util/helpers';
import { useErrorBoundary } from 'preact/hooks';
import { setupRerender } from 'preact/test-utils';

/** @jsx createElement */

describe('errorBoundary', () => {
	/** @type {HTMLDivElement} */
	let scratch, rerender;

	beforeEach(() => {
		scratch = setupScratch();
		rerender = setupRerender();
	});

	afterEach(() => {
		teardown(scratch);
	});

	it('catches errors', () => {
		const Throws = () => {
			throw new Error('test');
		};

		const App = props => {
			const [err] = useErrorBoundary();
			return err ? <p>Error</p> : <Throws />;
		};

		render(<App />, scratch);
		rerender();
		expect(scratch.innerHTML).to.equal('<p>Error</p>');
	});

	it('calls the errorBoundary callback', () => {
		const spy = sinon.spy();
		const error = new Error('test');
		const Throws = () => {
			throw error;
		};

		const App = props => {
			const [err] = useErrorBoundary(spy);
			return err ? <p>Error</p> : <Throws />;
		};

		render(<App />, scratch);
		rerender();
		expect(scratch.innerHTML).to.equal('<p>Error</p>');
		expect(spy).to.be.calledOnce;
		expect(spy).to.be.calledWith(error);
	});
});

@@ -481,32 +481,68 @@
 rrors', () =%3E %7B%0A
+%09%09let resetErr,%0A%09%09%09success = false;%0A
 %09%09const Throws =
@@ -614,32 +614,39 @@
  %7B%0A%09%09%09const %5Berr
+, reset
 %5D = useErrorBoun
@@ -658,35 +658,83 @@
 );%0A%09%09%09re
-turn err ? %3Cp%3EError
+setErr = reset;%0A%09%09%09return err ? %3Cp%3EError%3C/p%3E : success ? %3Cp%3ESuccess
 %3C/p%3E : %3C
@@ -845,16 +845,119 @@
 r%3C/p%3E');
+%0A%0A%09%09success = true;%0A%09%09resetErr();%0A%09%09rerender();%0A%09%09expect(scratch.innerHTML).to.equal('%3Cp%3ESuccess%3C/p%3E');
 %0A%09%7D);%0A%0A%09

add test for resetting the error