用酶获取子元素

时间:2019-06-06 20:14:28

标签: javascript reactjs jestjs enzyme

我想运行一个测试,以便对于我的浅酶包装纸,我可以确定该包装纸是否包含正确的子元素。例如,给定以下代码和定义的包装器,我想运行某种函数或某种东西(someFn()),以便返回包装器中的子元素(在本例中为<p>this is some text</p>) 。有没有办法做到这一点?目前wrapper.getElement()会给我<div test-attr="div"><p>this is some text</p></div>,这并不是我要找的东西。谢谢!

sampleComponent.js:

import React from 'react';

const SampleComponent = () => (
  <div test-attr="div">
    <p>this is some text</p>
  </div>
);

export default SampleComponent;

sampleComponent.test.js:

import React from 'react';
import { shallow } from 'enzyme';
import SampleComponent from './sampleComponent';

test('renders icon without errors', () => {
  const wrapper = shallow(<SampleComponent />);
  const div = wrapper.find('[test-attr="div"]');
  const expectedChildElement = <p>this is some text</p>;
  expect(div.someFn()).toEqual(expectedChildElement);
});

1 个答案:

答案 0 :(得分:1)

您可以将children()html()一起使用。

这是有效的测试用例:

import React from 'react';
import { shallow } from 'enzyme';
import SampleComponent from './sampleComponent';

test('renders icon without errors', () => {
    const wrapper = shallow(<SampleComponent />);
    const div = wrapper.find('[test-attr="div"]');
    const expectedChildElement = "<p>this is some text</p>";
    //console.log(div.children().debug());
    expect(div.children().html()).toEqual(expectedChildElement);
});