javascript - 使用 Enzyme 测试组合的 Reactjs 组件

标签 javascript reactjs enzyme

我遵循了 React 文档的建议,通过组合创建了一个专门的组件:

export default class AlertPanel extends React.Component {

    constructor(props) {
        super(props);
    }

    render() {
                textRows = <div>{this.props.text}</div>;
            }

            return (
               <Alert bsStyle={this.props.style} onDismiss={this.props.onDismiss}>
                    {textRows} 
               </Alert>
            );
    }

...和...

import React from 'react';
import AlertPanel from './AlertPanel';

export default class SpecialAlertPanel extends React.Component {

    constructor(props) {
        super(props);
    }

    render() {
        return (
          <AlertPanel text="special" />
        ) ;
    }
}

AlertPanel 已通过测试:

it( 'should render AlertPanel to a div', function() { 
    const wrapper = shallow( <AlertPanel /> );
    expect( wrapper.type() ).to.eql( 'div' );
});

我认为等效测试适用于 SpecialAlertPanel:

it( 'should render SpecialAlertPanel to a div', function() {
    const wrapper = shallow( <SpecialAlertPanel /> );
    expect( wrapper.type() ).to.eql( 'div' );
});

但是这个测试失败了:

expected [Function: AlertPanel] to deeply equal 'div'

我的测试或代码有问题吗?

最佳答案

由于您进行浅层渲染,SpecialAlertPanel 会渲染为 AlertPanel,但不会“更深”( http://airbnb.io/enzyme/docs/api/ShallowWrapper/shallow.html )

很可能你需要类似的东西

it( 'should render SpecialAlertPanel to a div', function() {
  const wrapper = shallow( <SpecialAlertPanel /> );
  expect(wrapper.find(AlertPanel).shallow().type()).to.eql('div');
});

关于javascript - 使用 Enzyme 测试组合的 Reactjs 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41741089/

相关文章:

javascript - 如何在 django 中按列过滤表

javascript - 单元测试 React 点击外部组件

reactjs - enzyme 渲染包装组件而不是基础组件

javascript - Discord.js 获取 channel 中所有消息的数组

javascript - 聊天框总是滚动到底部到最后一行聊天

javascript - 从 javascript 文件中提取信息到远程站点

javascript - 如何将 "raw"DOM 事件转换为 React SyntheticEvent?

ruby-on-rails - 如何将 React 应用程序和 Rails API 部署到 Heroku?

reactjs - React redux api 每 x 秒轮询一次

javascript - 确保为 enzyme 加载 dom 环境