最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论