Enzymeは、Reactコンポーネントの出力のアサート、操作、トラバースを簡単に行えるようにする、React用のJavaScriptテストユーティリティです。Airbnbで開発され、後に独立した組織に移管されました。
EnzymeのAPIは直感的で柔軟であることが目的であり、jQueryのDOM操作およびトラバース用APIをまねています。
Enzymeは、使用するテストランナーまた場合アサーションライブラリについて意見を持たず、一般に普及しているすべてのテストランナーおよびアサーションライブラリと互換性があるはずです。Enzymeのドキュメントと例ではmochaとchaiを使用していますが、選択したフレームワークまで外挿できるはずです。
Enzymeの使用を始めるには、npmでインストールします。
npm i --save-dev enzyme
現在、EnzymeはReact 0.14.x
とReact 0.13.x
の両方に対応しています。この互換性を確保するため、一部の依存関係をpackage.json
に明示的に記載することはできません。
React 0.14
を使用する場合、enzyme
に加えて、それらがまだインストールされていない場合は、次のnpmモジュールも確実にインストールする必要があります。
npm i --save-dev react-addons-test-utils
npm i --save-dev react-dom
import { shallow } from 'enzyme';
describe('<MyComponent />', () => {
it('should render three <Foo /> components', () => {
const wrapper = shallow(<MyComponent />);
expect(wrapper.find(Foo)).to.have.length(3);
});
it('should render an `.icon-star`', () => {
const wrapper = shallow(<MyComponent />);
expect(wrapper.find('.icon-star')).to.have.length(1);
});
it('should render children when passed in', () => {
const wrapper = shallow(
<MyComponent>
<div className="unique" />
</MyComponent>
);
expect(wrapper.contains(<div className="unique" />)).to.be.true;
});
it('simulates click events', () => {
const onButtonClick = sinon.spy();
const wrapper = shallow(
<Foo onButtonClick={onButtonClick} />
);
wrapper.find('button').simulate('click');
expect(onButtonClick.calledOnce).to.be.true;
});
});
完全なAPIドキュメントを参照してください。
import {
describeWithDOM,
mount,
spyLifecycle,
} from 'enzyme';
describeWithDOM('<Foo />', () => {
it('calls componentDidMount', () => {
spyLifecycle(Foo);
const wrapper = mount(<Foo />);
expect(Foo.prototype.componentDidMount.calledOnce).to.be.true;
});
it('allows us to set props', () => {
const wrapper = mount(<Foo bar="baz" />);
expect(wrapper.props().bar).to.equal("baz");
wrapper.setProps({ bar: "foo" });
expect(wrapper.props().bar).to.equal("foo");
});
it('simulates click events', () => {
const onButtonClick = sinon.spy();
const wrapper = mount(
<Foo onButtonClick={onButtonClick} />
);
wrapper.find('button').simulate('click');
expect(onButtonClick.calledOnce).to.be.true;
});
});
完全なAPIドキュメントを参照してください。
import { render } from 'enzyme';
describe('<Foo />', () => {
it('renders three `.foo-bar`s', () => {
const wrapper = render(<Foo />);
expect(wrapper.find('.foo-bar').length).to.equal(3);
});
it('rendered the title', () => {
const wrapper = render(<Foo title="unique" />);
expect(wrapper.text()).to.contain("unique");
});
});
完全なAPIドキュメントを参照してください。