Skip to content

Instantly share code, notes, and snippets.

@carmichaelize
Last active July 19, 2017 20:07
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 carmichaelize/dd0514fd41a2f53e2e1d2568629d8987 to your computer and use it in GitHub Desktop.
Save carmichaelize/dd0514fd41a2f53e2e1d2568629d8987 to your computer and use it in GitHub Desktop.
Shallow Rendering a Redux Component in React Tests
import React, { Component } from 'react';
import { connect } from 'react-redux';
export class FooBar extends Component {
greet() {
return `Hello ${store.foo} ${store.bar}!`;
}
render() {
return (
<h1>{this.props.foo} {this.props.bar}</h1>
);
}
}
const mapStateToProps = (store) => {
return {
foo: 'Foo',
bar: 'Bar'
}
}
const mapDispatchToProps = (dispatch) => {
return {}
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(FooBar);
import React from 'react';
import { shallow } from 'enzyme';
import { ShallowMock } from './shallow-mock.jsx';
import { FooBar } from './foo-bar.jsx'; // The braces are important!
let store = {
foo: 'Foo',
bar: 'Bar'
};
describe('Component: FooBar', () => {
it('should create the FooBar component', () => {
const foobar = shallow(
ShallowMock(<FooBar />, store)
);
expect(foobar).toBeTruthy();
});
it('greet method should output a message', () => {
const foobar = shallow(
ShallowMock(<FooBar />, store)
);
expect(foobar.instance().greet()).toEqual(`Hello ${store.foo} ${store.bar}!`);
});
});
import React from 'react';
export const ShallowMock = (Component, props) => {
return React.cloneElement(
Component,
props
);
};
export default ShallowMock;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment