Skip to content

Commit

Permalink
feat: add bindElementToQueries utility function for libraries using t…
Browse files Browse the repository at this point in the history
…his API (#18)

* Add bindQueriesToElement utility function for libraries using this API

* Add documentation and update contributors

* Rename to bindElementToQueries as this seems to be more appropriate

Closes #17
  • Loading branch information
dfcook authored and Kent C. Dodds committed Apr 11, 2018
1 parent f2683d9 commit 4410b4c
Show file tree
Hide file tree
Showing 5 changed files with 34 additions and 8 deletions.
11 changes: 11 additions & 0 deletions .all-contributorsrc
Expand Up @@ -160,6 +160,17 @@
"doc",
"example"
]
},
{
"login": "dfcook",
"name": "Daniel Cook",
"avatar_url": "https://avatars3.githubusercontent.com/u/10348212?v=4",
"profile": "https://github.com/dfcook",
"contributions": [
"code",
"doc,
"test"
]
}
]
}
7 changes: 7 additions & 0 deletions README.md
Expand Up @@ -83,6 +83,7 @@ when a real user uses it.
* [Using other assertion libraries](#using-other-assertion-libraries)
* [`TextMatch`](#textmatch)
* [`query` APIs](#query-apis)
* [`bindElementToQueries`](#bindElementToQueries)
* [Debugging](#debugging)
* [Implementations](#implementations)
* [FAQ](#faq)
Expand Down Expand Up @@ -468,6 +469,12 @@ expect(submitButton).toBeNull() // it doesn't exist
expect(submitButton).not.toBeInTheDOM()
```

## `bindElementToQueries`

`bindElementToQueries` takes a DOM element and binds it to the raw query functions, allowing them
to be used without specifying a container. It is the recommended approach for libraries built on this API
and is in use in `react-testing-library` and `vue-testing-library`.

## Debugging

When you use any `get` calls in your test cases, the current state of the `container`
Expand Down
10 changes: 2 additions & 8 deletions src/__tests__/helpers/test-utils.js
@@ -1,15 +1,9 @@
import * as queries from '../../queries'
import {bindElementToQueries} from '../../bind-element-to-queries'

function render(html) {
const container = document.createElement('div')
container.innerHTML = html
const containerQueries = Object.entries(queries).reduce(
(helpers, [key, fn]) => {
helpers[key] = fn.bind(null, container)
return helpers
},
{},
)
const containerQueries = bindElementToQueries(container)
return {container, ...containerQueries}
}

Expand Down
13 changes: 13 additions & 0 deletions src/bind-element-to-queries.js
@@ -0,0 +1,13 @@
import * as queries from './queries'

function bindElementToQueries(element) {
return Object.entries(queries).reduce(
(helpers, [key, fn]) => {
helpers[key] = fn.bind(null, element)
return helpers
},
{},
)
}

export {bindElementToQueries}
1 change: 1 addition & 0 deletions src/index.js
Expand Up @@ -9,3 +9,4 @@ export * from './wait'
export * from './wait-for-element'
export * from './matches'
export * from './events'
export * from './bind-element-to-queries'

0 comments on commit 4410b4c

Please sign in to comment.