diff --git a/src/__tests__/get-queries-for-element.js b/src/__tests__/get-queries-for-element.js new file mode 100644 index 00000000..1a6afba8 --- /dev/null +++ b/src/__tests__/get-queries-for-element.js @@ -0,0 +1,31 @@ +import {getQueriesForElement} from '../get-queries-for-element' +import {queries} from '..' + +test('uses default queries', () => { + const container = document.createElement('div') + const boundQueries = getQueriesForElement(container) + expect(Object.keys(boundQueries)).toEqual(Object.keys(queries)) +}) + +test('accepts custom queries', () => { + const container = document.createElement('div') + const customQuery = jest.fn() + const boundQueries = getQueriesForElement(container, { + ...queries, + customQuery, + }) + expect(boundQueries.customQuery).toBeDefined() +}) + +test('binds functions to container', () => { + const container = document.createElement('div') + const mock = jest.fn() + function customQuery(element) { + return mock(element) + } + const boundQueries = getQueriesForElement(container, { + customQuery, + }) + boundQueries.customQuery() + expect(mock).toHaveBeenCalledWith(container) +}) diff --git a/src/get-queries-for-element.js b/src/get-queries-for-element.js index a633de60..6dfd29b7 100644 --- a/src/get-queries-for-element.js +++ b/src/get-queries-for-element.js @@ -1,6 +1,15 @@ -import * as queries from './queries' +import * as defaultQueries from './queries' -function getQueriesForElement(element) { +/** + * @typedef {{[key: string]: Function}} FuncMap + */ + +/** + * @param {HTMLElement} element container + * @param {FuncMap} queries object of functions + * @returns {FuncMap} returns object of functions bound to container + */ +function getQueriesForElement(element, queries = defaultQueries) { return Object.entries(queries).reduce((helpers, [key, fn]) => { helpers[key] = fn.bind(null, element) return helpers diff --git a/typings/get-queries-for-element.d.ts b/typings/get-queries-for-element.d.ts index 14fd91bc..f9c8482b 100644 --- a/typings/get-queries-for-element.d.ts +++ b/typings/get-queries-for-element.d.ts @@ -12,4 +12,7 @@ export type BoundFunctions = {[P in keyof T]: BoundFunction} export function getQueriesForElement( element: HTMLElement, + queriesToBind: + | BoundFunctions + | BoundFunctions[], ): BoundFunctions