首页 > 解决方案 > 反应笑话和酶,找到具有隐藏属性的“选项”

问题描述

我正在测试一个组合框,它的占位符值如下:

<option key='blankChoice' hidden value>{blankChoice}</option>

我想运行一个测试,检查空白选项是否实际附加到我的组合框,因此我做了以下操作:

beforeEach(() => {
    wrapper = mount(<ComboBox options={options} />)
});

afterEach(() => {
    wrapper.unmount();
})
test('Combobox has 1 hidden options', () => {
    const elem = wrapper.find('option')
    expect(elem).toHaveAttribute("hidden").toBe(1)
})

以上向我返回了一个错误:

接收到的值必须是 HTMLElement 或 SVGElement。

我有点理解这个错误,但我怀疑我的一般方法是否正确。因此,我如何测试我的 comobobx 是否隐藏了 1<option>

标签: reactjsjestjsenzyme

解决方案


wrapper.find()返回ReactWrapper哪个是对象。您需要使用.getDOMNode() => DOMComponent返回当前包装器的最外层 DOMComponent。

例如

ComboBox.tsx

import React from 'react';

export default function ComboBox() {
  return (
    <div>
      <select>
        <option key="blankChoice" hidden></option>
      </select>
    </div>
  );
}

ComboBox.test.tsx

import { mount } from 'enzyme';
import '@testing-library/jest-dom/extend-expect';
import React from 'react';
import ComboBox from './ComboBox';

describe('68393118', () => {
  let wrapper;
  beforeEach(() => {
    wrapper = mount(<ComboBox />);
  });

  afterEach(() => {
    wrapper.unmount();
  });
  test('Combobox has 1 hidden options', () => {
    const elem = wrapper.find('option');
    expect(elem.getDOMNode()).toHaveAttribute('hidden');
  });
});

测试结果:

 PASS  examples/68393118/ComboBox.test.tsx (10.678 s)
  68393118
    ✓ Combobox has 1 hidden options (53 ms)

--------------|---------|----------|---------|---------|-------------------
File          | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
--------------|---------|----------|---------|---------|-------------------
All files     |     100 |      100 |     100 |     100 |                   
 ComboBox.tsx |     100 |      100 |     100 |     100 |                   
--------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        11.539 s

推荐阅读