Skip to content

Instantly share code, notes, and snippets.

@francisngo
Last active January 2, 2018 19:58
Show Gist options
  • Save francisngo/13956094961ffb4aca68f6f14fe2258a to your computer and use it in GitHub Desktop.
Save francisngo/13956094961ffb4aca68f6f14fe2258a to your computer and use it in GitHub Desktop.
Used Jest to unit-test a React component
import App from './App';
import React from 'react';
import { configure, shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
configure({ adapter: new Adapter() });
describe('App', () => {
it('should have the `th` "Todos"', () => {
const wrapper = shallow(
<App />
);
expect(
wrapper.contains(<th>Todos</th>)
).toBe(true);
});
it('should have a `input` element', () => {
const wrapper = shallow(
<App />
);
expect(
wrapper.containsMatchingElement(
<input />
)
).toBe(true);
});
it('should have a `button` element', () => {
const wrapper = shallow(
<App />
);
expect(
wrapper.containsMatchingElement(
<button>Add todo</button>
)
).toBe(true);
});
describe('Input changes', () => {
const wrapper = shallow(
<App />
);
const todo = 'Do the thing';
beforeEach(() => {
const input = wrapper.find('input').first();
input.simulate('change', {
target: { value: todo }
})
});
it('should update the state property `todo`', () => {
expect(wrapper.state().todo).toEqual(todo);
});
describe('and then submits the form', () => {
beforeEach(() => {
const form = wrapper.find('form').first();
form.simulate('submit', {
preventDefault: () => {},
});
});
it('should add the todo to state', () => {
expect(wrapper.state().todos).toContain(todo);
});
it('should render the item in the table', () => {
expect(wrapper.containsMatchingElement(
<td>{todo}</td>
)).toBe(true);
});
it('should clear the input field', () => {
const input = wrapper.find('input').first();
expect(input.props().value).toEqual('');
});
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment