首页 > 解决方案 > 如何使用 jest 测试反应组件的标题?

问题描述

我有一个简单的组件,其中包括两个按钮和标题字段。到目前为止,我测试了按钮点击,但我想测试<h3>标签中的标题文本字段。

我的组件

class Popup extends React.Component {
    render() {
        return (
            <div className="popupOuter">
                <div className="popupInner text-center">
                    <br/>
                    <h3>{this.props.config.text}</h3>
                    <br/>
                    <div>
                    <Button type='NoButton' value={'No'} onClick={this.props.config.back} />
                    <Button type = 'YesButton' value={'Yes'} onClick={this.props.config.next}/>
                    </div>
                </div>
            </div>
        );
    }
}

我的测试

 test('Text test ', ()=>{
        const component = shallow(
            <Popup config={config}/>
        );
        expect(component.find('h3')).toEqual("h3");
    });

我的测试失败了

错误:expect(received).toEqual(expected) // 深度相等 Expected: "h3" Received: {}

什么地方出了错?请解释一下?

谢谢。

标签: reactjsunit-testingjestjsenzymeweb-component-tester

解决方案


.find(selector) => ShallowWrapper返回浅包装,显然,浅包装不等于字符串h3。如果你想得到这个h3浅包装的文本,你需要在浅包装上调用.text() => String

例如

index.tsx

import React from 'react';
const Button = (props) => <button></button>;
export class Popup extends React.Component {
  render() {
    return (
      <div className="popupOuter">
        <div className="popupInner text-center">
          <br />
          <h3>{this.props.config.text}</h3>
          <br />
          <div>
            <Button type="NoButton" value={'No'} onClick={this.props.config.back} />
            <Button type="YesButton" value={'Yes'} onClick={this.props.config.next} />
          </div>
        </div>
      </div>
    );
  }
}

index.test.tsx

import { Popup } from './';
import { shallow } from 'enzyme';

describe('60759790', () => {
  it('should render text for h3', () => {
    const mProps = { config: { text: 'h3' } };
    const wrapper = shallow(<Popup {...mProps}></Popup>);
    expect(wrapper.find('h3').text()).toEqual('h3');
  });
});

单元测试结果:

 PASS  stackoverflow/60759790/index.test.jsx (8.126s)
  60759790
    ✓ should render text for h3 (10ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        9.418s

推荐阅读