Skip to content

Commit

Permalink
Add tests for useElementRef
Browse files Browse the repository at this point in the history
  • Loading branch information
robertknight committed Oct 27, 2021
1 parent 74a6f9b commit 2382576
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions src/shared/test/hooks-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { render } from 'preact';

import { useElementRef } from '../hooks';

describe('shared/hooks', () => {
it('returns ref if accessed when non-null', () => {
function Widget({ callback }) {
const ref = useElementRef(HTMLButtonElement);
return (
<button ref={ref} onClick={() => callback(ref.current.localName)} />
);
}

const callback = sinon.stub();
const container = document.createElement('div');
render(<Widget callback={callback} />, container);
container.querySelector('button').click();

assert.calledWith(callback, 'button');
});

it('throws if accessed when `null`', () => {
function Widget() {
const ref = useElementRef(HTMLElement);
return <div>{ref.current.localName}</div>;
}

assert.throws(() => {
render(<Widget />, document.createElement('div'));
}, 'Tried to access null ref');
});
});

0 comments on commit 2382576

Please sign in to comment.