javascript - 使用 enzyme 获取子元素

标签 javascript reactjs jestjs enzyme

我想运行一个测试,以便对于我的浅层 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/

相关文章:

javascript - IE 中的 JQuery focusOut 问题

reactjs - 错误和加载是否应该存储在 store 或 state 中?

javascript - 单击时显示 react 组件

unit-testing - 如何使用 Jest 监视 Vuejs 应用程序上的 window.location.assign?

javascript - Button 的悬停过渡效果

javascript - Javascript/JQuery 中的多个 DIV 碰撞检测

reactjs - 如果存在则从商店获取数据,否则在 React 中调用 API

reactjs - 使用自定义 Hook 在组件上用 Jest 进行测试

javascript - 配置 Jest moduleNameMapper 不起作用

javascript - JQuery 'thinks' 我想要 AJAX 另一个域