https://github.com/kentcdodds/react-test-context-provider
A function that allows you to specify context to pass to a child component (intended for testing only).
https://github.com/kentcdodds/react-test-context-provider
Last synced: 11 months ago
JSON representation
A function that allows you to specify context to pass to a child component (intended for testing only).
- Host: GitHub
- URL: https://github.com/kentcdodds/react-test-context-provider
- Owner: kentcdodds
- License: mit
- Created: 2016-09-13T21:39:45.000Z (over 9 years ago)
- Default Branch: main
- Last Pushed: 2021-01-25T23:17:24.000Z (about 5 years ago)
- Last Synced: 2025-03-28T13:11:50.246Z (12 months ago)
- Language: JavaScript
- Homepage: https://npmjs.com/package/react-test-context-provider
- Size: 3.91 KB
- Stars: 48
- Watchers: 2
- Forks: 9
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
- awesome-list - react-test-context-provider
README
# react-test-context-provider
A function that allows you to specify context to pass to a child component (intended for testing only).
## Installation
This module is distributed via [npm][npm] which is bundled with [node][node] and should
be installed as one of your project's `devDependencies`:
```
npm install --save-dev react-test-context-provider
```
## Usage
```javascript
var getContextProvider = require('react-test-context-provider')
var contextObject = {color: 'blue'} // the context you want to provide to the children components
var reactElement = getElementWithContext(contextObject, ) // returns the react element as rendered with the given context
```
In this example, I'm using the [Jest](http://facebook.github.io/jest/) testing framework.
**Button.js**
```javascript
import React, {PropTypes} from 'react'
export default function Button({children}, {color}) {
// function components receive context as the second argument
return {children}
}
Button.propTypes = {children: PropTypes.any.isRequired}
Button.contextTypes = {color: PropTypes.string}
```
**Button.test.js**
```javascript
import React from 'react'
import renderer from 'react-test-renderer'
import getElementWithContext from 'react-test-context-provider'
import Button from './Button'
test('styles the button with a background of the context color', () => {
const element = getElementWithContext({color: 'blue'}, Click Me)
const component = renderer.create(element)
expect(component).toMatchSnapshot()
// NOTE: This API is also curried, so you can provide the context first and the children later:
// import getContextProvider from 'react-test-context-provider'
// const getElementWithBlueColorContext = getContextProvider({color: 'blue'})
// const element = getElementWithBlueColorContext(Click Me)
})
```
## LICENSE
MIT
[npm]: https://www.npmjs.com/
[node]: https://nodejs.org