Enzyme

React 的 JavaScript 測試工具
19,571
作者Leland Richardson

Enzyme 是一個 React 的 JavaScript 測試工具,它可以讓您更容易地斷言、操作和遍歷您的 React 元件的輸出。它最初在 Airbnb 開發,後來轉移到一個獨立的組織

Enzyme 的 API 旨在通過模仿 jQuery 的 DOM 操作和遍歷 API 來實現直觀和靈活。

Enzyme 對於您使用的測試執行器或斷言庫沒有任何偏見,並且應該與所有主要的測試執行器和斷言庫相容。Enzyme 的文件和範例使用 mochachai,但您應該能夠將其推廣到您選擇的框架。



安裝

要開始使用 Enzyme,您可以簡單地使用 npm 安裝它

npm i --save-dev enzyme

Enzyme 目前與 React 0.14.xReact 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 文件

JSDOM 完全渲染

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 文件