为什么在使用完整渲染或浅渲染时,带有组件道具的酶 find() 的工作方式不同?

Why doesn't enzymes find() with component props work the same way when using full rendering or shallow rendering?

根据 shallow rendering and full rendering (mount) 的 find() 酶文档,应该能够使用 props 的值查找组件。这似乎对完整和浅层渲染的工作方式不同认为我的文档似乎没有解释预期会有任何差异。

正在测试的示例组件

import React, { Component } from 'react';

class Foo extends Component {
  render() {
    return (
      <div>
        <h1>Foo</h1>
        {this.props.children}
      </div>
    );
  }
}

class Bar extends Component {
  render() {
    return (<h1>Bar</h1>);
  }
}

class FindTest extends Component {
  render() {
    return (
      <div>
        <span spanProp="spanValue">Enzyme Find Test</span>
        <Foo fooProp="fooValue">
          <Bar barProp="barValue" />
        </Foo>
      </div>
    );
  }
}

export default FindTest;
export { Foo, Bar };

示例测试文件

import React from 'react';
import { shallow, mount } from 'enzyme';
import { expect } from 'chai';

import FindTest, { Foo, Bar } from 'components/FindTest/FindTest.js';

describe('<FindTest />', () => {
  it('can find using props with shallow rendering', () => {
    const wrapper = shallow(<FindTest />);
    // Passes
    expect(wrapper.find({ spanProp: 'spanValue' })).to.have.length(1);
    // Passes
    expect(wrapper.find({ fooProp: 'fooValue' })).to.have.length(1);
    // Passes
    expect(wrapper.find({ barProp: 'barValue' })).to.have.length(1);
    // Passes
    expect(wrapper.find(Foo).find({ barProp: 'barValue' })).to.have.length(1);
  });

  it('can find using props with mount rendering', () => {
    const wrapper = mount(<FindTest />);
    //Passes
    expect(wrapper.find({ spanProp: 'spanValue' })).to.have.length(1);
    // Fails
    expect(wrapper.find({ fooProp: 'fooValue' })).to.have.length(1);
    // Fails
    expect(wrapper.find({ barProp: 'barValue' })).to.have.length(1);
    // Fails
    expect(wrapper.find(Foo).find({ barProp: 'barValue' })).to.have.length(1);
  });
});

在挂载模式下测试失败,因为酶使用 react-addons-test-utils 在构造函数中将组件呈现为可视 dom,并且 React 不能在元素中使用动态属性和动态属性 将是 striped.if 你需要你必须使用以数据开头的动态属性,例如:data-属性-value.see:https://facebook.github.io/react/warnings/unknown-prop.html & https://github.com/holi-java/getstarted-react/blob/master/test/13.react-unknown-prop.test.js

renderWithOptions = (node, options) => {
   if (options.attachTo) {
      return React.render(node, options.attachTo);
    }
    return TestUtils.renderIntoDocument(node);
};

截至 2017 年 2 月,这似乎是一个错误。

正如@holi-java 在他上面的评论中提到的。如果节点是反应组件,则安装遍历的 instMatchesObjectProps 方法不会 return 节点。

此现有错误是在 Enzyme 项目中发现的 https://github.com/airbnb/enzyme/issues/376 and this PR are out to fix the issues https://github.com/airbnb/enzyme/pull/377