Skip to content

Instantly share code, notes, and snippets.

@michelmattos
Created March 23, 2017 09:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michelmattos/9fa115102ca7744f236961bfb0a92b60 to your computer and use it in GitHub Desktop.
Save michelmattos/9fa115102ca7744f236961bfb0a92b60 to your computer and use it in GitHub Desktop.
A helper module for testing React components using jsdom, jquery and chai-jquery
import { renderComponent, expect } from './testHelper'
import CommentBox from './CommentBox'
describe('CommentBox', () => {
let component
beforeEach(() => {
component = renderComponent(CommentBox)
})
it('has the correct class', () => {
expect(component).to.have.class('comment-box')
})
it('has a text area', () => {
expect(component.find('textarea')).to.exist
})
it('has a button', () => {
expect(component.find('button')).to.exist
})
describe('entering some text', () => {
beforeEach(() => {
component.find('textarea').simulate('change', 'new comment')
})
it('shows that text in the textarea', () => {
expect(component.find('textarea')).to.have.value('new comment')
})
it('when submitted, clears the input', () => {
component.simulate('submit');
expect(component.find('textarea')).to.have.value('')
})
})
})
import jsdom from 'jsdom'
import jquery from 'jquery'
import React from 'react'
import ReactDOM from 'react-dom'
import TestUtils from 'react-addons-test-utils'
import { Provider } from 'react-redux'
import { createStore } from 'redux'
import reducers from '../src/reducers'
import chai, { expect } from 'chai'
import chaiJquery from 'chai-jquery'
// Set up testing environment to run like a browser in the command line
global.document = jsdom.jsdom('<!doctype html><html><body></body></html>')
global.window = global.document.defaultView
global.navigator = global.window.navigator
const $ = jquery(global.window)
// Build 'renderComponent' helper that should render a given react class
function renderComponent(ComponentClass, props, state) {
const componentInstance = TestUtils.renderIntoDocument(
<Provider store={createStore(reducers, state)}>
<ComponentClass {...props} />
</Provider>
)
return $(ReactDOM.findDOMNode(componentInstance))
}
// Build helper for simulating events
$.fn.simulate = function(eventName, value) {
if (value) {
this.val(value)
}
TestUtils.Simulate[eventName](this[0])
}
// Set up chai-jquery
chaiJquery(chai, chai.util, $)
// Export functions
export { renderComponent, expect }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment