enzyme之shallow渲染

shallow rendering可以把组件当做一个单元来测试,而且确保不会因为子组件的行为而直接出现断言(Shallow rendering is useful to constrain yourself to testing a component as a unit, and to ensure that your tests aren’t indirectly asserting on behavior of child components.)

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.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);
  });

});

shallow(node[, options]) => ShallowWrapper

参数

  1. node (ReactElement)要渲染的节点

  2. options (对象 [可选]):

  3. options.context: (对象 [可选]): 传给组件的Context

返回

ShallowWrapper:这是一个cheerio的解析对象

API

  • .find(selector) => ShallowWrapper
    找到所有匹配的节点

  • .findWhere(predicate) => ShallowWrapper
    找到所有渲染树下满足函数内判断的节点

  • .filter(selector) => ShallowWrapper
    过滤匹配的节点

  • .filterWhere(predicate) => ShallowWrapper

  • .contains(nodeOrNodes) => Boolean

  • .containsMatchingElement(node) => Boolean

  • .containsAllMatchingElements(nodes) => Boolean

  • .containsAllMatchingElements(nodes) => Boolean

  • .equals(node) => Boolean

  • .matchesElement(node) => Boolean

  • .hasClass(className) => Boolean

  • .is(selector) => Boolean

  • .isEmpty() => Boolean

  • .not(selector) => ShallowWrapper

  • .children() => ShallowWrapper

  • .childAt(index) => ShallowWrapper

  • .parents() => ShallowWrapper

  • .parent() => ShallowWrapper

  • .closest(selector) => ShallowWrapper

  • .shallow([options]) => ShallowWrapper

  • .render() => CheerioWrapper

参照这里,不一一列举,方法和jQuery

    原文作者:chezhe
    原文地址: https://segmentfault.com/a/1190000007478466
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞