javascript - React Enzyme get all classes even if passed by other components - Stack Overflow

Say I haveconst BaseComponent = (props) => {const classNames = ['base-ponent', props.class

Say I have

const BaseComponent = (props) => {
    const classNames = ['base-ponent', props.className];
    return (
        <div className={classNames.join(' ')}>
            {props.children}
        </div>
    )
};

const SomeComponent = () => {
    return (
        <BaseComponent
            className="foo-bar"
        >
            Hello
        </BaseComponent>
    );
}

The rendered dom here would be <div class="base-ponent foo-bar">Hello</div>

Now, if I shallow mount SomeComponent and test the classes, only foo-bar is available:

const dom = shallow(<SomeComponent/>);
console.log(dom.hassClass('base-ponent')); // es out as false

I understand that only foo-bar was passed as the class to SomeComponent but how do I validate all other classes here too?

Say I have

const BaseComponent = (props) => {
    const classNames = ['base-ponent', props.className];
    return (
        <div className={classNames.join(' ')}>
            {props.children}
        </div>
    )
};

const SomeComponent = () => {
    return (
        <BaseComponent
            className="foo-bar"
        >
            Hello
        </BaseComponent>
    );
}

The rendered dom here would be <div class="base-ponent foo-bar">Hello</div>

Now, if I shallow mount SomeComponent and test the classes, only foo-bar is available:

const dom = shallow(<SomeComponent/>);
console.log(dom.hassClass('base-ponent')); // es out as false

I understand that only foo-bar was passed as the class to SomeComponent but how do I validate all other classes here too?

Share Improve this question asked Jan 8, 2018 at 19:30 KoushaKousha 36.4k59 gold badges188 silver badges314 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

What if you use the .prop API.

expect(dom.find('div').prop('className'))
  .to.be.equal('base-ponent foo-bar');

shallow() does only render the top level ponent which does not include your other class. You can use dive() to let it render the one ponent one level deeper. dive() renders the only one non-DOM child of the wrapper it was called on.

const dom = shallow(<SomeComponent/>);
console.log(dom.dive().hasClass('base-ponent')); // now es out as true

If you want inspect the whole DOM you will have to use render() instead of shallow().

Also not that a call to html() on a ShallowWrapper will always return the markup of a full render no matter if it was a shallow render or not.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745531302a4631707.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信