【问题标题】:How to test React components inside react-responsive tags如何在 react-responsive 标签中测试 React 组件
【发布时间】:2019-03-11 18:49:02
【问题描述】:

<MyComponent> 组件中,我使用react-responsive <MediaQuery> 组件来区分渲染移动和桌面内容。

export class MyComponent extends React.Component {

  //...

    render() {
      <MediaQuery query="(max-width: 600)">
        <div className="inside-mobile">mobile view</div>
      </MediaQuery>
    }
}

我想使用enzyme 测试&lt;MyComponent&gt;render() 中的HTML,但似乎无法深入了解&lt;MediaQuery&gt; 的子元素:

it('should dive into <MediaQuery>', () => {
    const wrapper = mount(<Provider store={mockedStore}><MyComponent/></Provider>)
    const actual = wrapper.getDOMNode().querySelectorAll(".inside-mobile")       
    expect(actual).to.have.length(1)
}

console.log(wrapper.debug()) 表明 &lt;MediaQuery&gt; 内部的任何内容都没有被渲染。 我猜在测试中(没有实际的浏览器)window.width 未设置,这导致&lt;MediaQuery&gt; 组件不呈现任何内容。

我想做的事:

我希望能够使用enzymereact-responsive(或类似的东西,例如react-media)来测试&lt;MyComponent&gt; 的内容,以处理移动和桌面视口。

我尝试过的事情:

  • 通过使用enzymeshallowdive() 而不是mount 来规避此问题,但无济于事。
  • 使用react-media&lt;Media&gt;而不是react-responsive&lt;MediaQuery&gt;,默认情况下似乎将window.matchMedia()设置为true。但是,这也不起作用。

console.log(wrapper.debug()) 显示:

<MyComponent content={{...}}>
    <Media query="(min-width: 600px)" defaultMatches={true} />
</MyComponent>

【问题讨论】:

    标签: reactjs unit-testing media-queries enzyme chai-enzyme


    【解决方案1】:

    我找到了一个可行的解决方案,使用react-media 而不是react-responsive,通过模拟window.matchMedia 以便在测试期间将matches 设置为true

    为不同的视口创建特定的媒体组件:

    const Mobile = ({ children, content }) => <Media query="(max-width: 600px)" children={children}>{matches => matches ? content : "" }</Media>;
    const Desktop = ...
    

    使用特定的媒体组件:

    <MyComponent>
        <Mobile content={
            <div className="mobile">I'm mobile</div>
        }/>
        <Desktop content={...}/>
    </MyComponent>
    

    每个视口的测试内容:

    const createMockMediaMatcher = matches => () => ({
        matches,
        addListener: () => {},
        removeListener: () => {}
    });
    
    describe('MyComponent', () => {
        beforeEach(() => {
            window.matchMedia = createMockMediaMatcher(true);
        });
    
        it('should display the correct text on mobile', () => {
    
            const wrapper = shallow(<MyComponent/>);
            const mobileView = wrapper.find(Mobile).shallow().dive();
            const actual = mobileView.find(".mobile").text();
    
            expect(actual).to.equal("I'm mobile");
        });
    });
    

    【讨论】:

      猜你喜欢
      • 2017-01-01
      • 1970-01-01
      • 2019-09-25
      • 1970-01-01
      • 2021-10-24
      • 1970-01-01
      • 1970-01-01
      • 2021-09-19
      • 1970-01-01
      相关资源
      最近更新 更多