Created
August 4, 2016 13:06
-
Star
(121)
You must be signed in to star a gist -
Fork
(8)
You must be signed in to fork a gist
-
-
Save thevangelist/e2002bc6b9834def92d46e4d92f15874 to your computer and use it in GitHub Desktop.
The only React.js component test you'll ever need (Enzyme + Chai)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import { shallow } from 'enzyme'; | |
import MyComponent from '../src/my-component'; | |
const wrapper = shallow(<MyComponent/>); | |
describe('(Component) MyComponent', () => { | |
it('renders without exploding', () => { | |
expect(wrapper).to.have.length(1); | |
}); | |
}); |
For those of us using Jest, you would check the length with expect(wrapper).toHaveLength(1)
@chiedo Does it do that? I'm not seeing where this happens.
For those in 2018 using create-react-app: https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/template/README.md#testing-components
tl;dr; use:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
it('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(<App />, div);
});
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@michel-weber (and others ending up here) the wrapper returned by
shallow
is not an instance of a React component.It is an array-like object (having a
length
property).It is the same as what you get back from
wrapper.find('...something...')
. Which is an array of items that match your selector.With the result of
shallow
this is generally only one component. But one or more doesn't matter in this case. What matters is that it isn't zero, as that lets you know rendering failed.Also, without chai, you'd write
assert(wrapper.length === 1);
.