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('', () => {

  it('should render three  components', () => {
    const wrapper = shallow();
    expect(wrapper.find(Foo)).to.have.length(3);
  });

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

  it('should render children when passed in', () => {
    const wrapper = shallow(
      
        
); expect(wrapper.contains(
)).to.equal(true); }); it('simulates click events', () => { const onButtonClick = sinon.spy(); const wrapper = shallow( ); 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

你可能感兴趣的:(react.js,testrunner,airbnb,karma)