なっく日報

技術やら生活やらのメモ

enzymeはReactコンポーネントのユニットテストに使えるかもしれない

時間がないので、ご紹介だけ。

github.com

というのを同僚のプロジェクトのpackage.jsonで見かけました。

↓な感じにReactコンポーネントテストが書けると。

import { shallow } from 'enzyme';
import sinon from 'sinon';

describe('<MyComponent />', () => {

  it('renders three <Foo /> components', () => {
    const wrapper = shallow(<MyComponent />);
    expect(wrapper.find(Foo)).to.have.length(3);
  });

  it('renders an `.icon-star`', () => {
    const wrapper = shallow(<MyComponent />);
    expect(wrapper.find('.icon-star')).to.have.length(1);
  });

  it('renders children when passed in', () => {
    const wrapper = shallow(
      <MyComponent>
        <div className="unique" />
      </MyComponent>
    );
    expect(wrapper.contains(<div className="unique" />)).to.equal(true);
  });

  it('simulates click events', () => {
    const onButtonClick = sinon.spy();
    const wrapper = shallow(
      <Foo onButtonClick={onButtonClick} />
    );
    wrapper.find('button').simulate('click');
    expect(onButtonClick.calledOnce).to.equal(true);
  });

});

airbnbリポジトリにあるし、この記事を書いた時点で、スター数も2700を超えているので 結構使える予感。

一点、アサーションchaiを使っているのだけ、好みでないので、power-assertで動くか試してみたいと思います。

(近いうちに・・・)