如何使用 Jest and/or Enzyme 获取嵌套在 React 组件中的元素的属性?

How do I get an attribute of an element nested in a React component using Jest and/or Enzyme?

我想测试一下图像是否已正确加载到 React 应用程序中。我决定检查嵌套在 React 组件中的 img 元素的 src 属性。我想使用 Jest 测试框架,如果需要,还想使用 Enzyme 测试实用程序。

通过深入研究浅层 React 测试组件的 Object.keys,我得出了以下解决方案。我不确定的行用星号表示。

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

it('should have the logo image', () => {
  const app = shallow(<App />);
  const img = app.find('img');
  const src = img.node.props.src; // ******
  expect(src).toBe('logo.svg');
});

这个解决方案确实有效,但它看起来有点复杂(它需要一个属性一个属性一个属性一个包装器)并且看起来有些晦涩(我无法轻易地在网上找到明确的说明)。那么,这是 correct/simplest 的方法吗?

about React element attributes doesn't seem to quite answer it for me even though the poster there also indicates having a hard time finding documentation about asserting a rendered attribute value. A number of other questions (e.g. , here and ) 处理 React/Jest/Enzyme 但不处理检索属性值。

经过一番挖掘,我发现了以下内容。问题中指示的行:

const src = img.node.props.src;

可以简化为:

const src = img.prop('src');

可以找到文档 here

如果有人知道这样做的非酶方法,我仍然有兴趣了解它。

使用 React Test Utilities:

it('should have the logo image', () => 
  const app = TestUtils.renderIntoDocument(<App/>);
  var image = TestUtils.findRenderedDOMComponentWithTag(app, 'img');
  expect(image.getDOMNode().getAttribute('src')).toEqual('logo.svg');
});

酶测试看起来更干净。

.node is not working 经过一番努力,我发现以下内容与上述问题的答案 100% 相关

  const src = img.getElement().props.src;

对我来说,效果如下

expect(companySelect.find('input').props()["disabled"]).toBe(true)

props() returns一个对象,具有选择器的所有属性,然后可以作为一个对象进行浏览。

希望这也有帮助....

https://airbnb.io/enzyme/docs/api/ReactWrapper/props.html

对我来说这很有效

expect(component.find('button').props().disabled).toBeTruthy();

@testing-library/jest-dom library provides a custom matcher toHaveAttribute。扩展 expect 子句后

import '@testing-library/jest-dom/extend-expect'

我们可以断言

const rect = document.querySelector('[data-testid="my-rect"]')
expect(rect).toHaveAttribute('width', '256')