我想运行一个测试,以便对于我的浅层 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);
});
最佳答案
您可以将 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);
});
关于javascript - 使用 enzyme 获取子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56484516/