reactjs - 如何测试 react 响应标签内的 react 组件

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

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

export class MyComponent extends React.Component {

  //...

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

我想测试<MyComponent>里面的HTML的render()使用enzyme ,但似乎无法深入研究 <MediaQuery> 的子元素:

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())显示里面什么都没有<MediaQuery>不过正在渲染。 我猜测是在测试中(没有实际的浏览器)window.width未设置会导致<MediaQuery>组件不渲染任何内容。

我想做的事情:

我希望能够测试<MyComponent>的内容使用 enzymereact-responsive (或类似的东西,如 react-media )来处理移动与桌面视口(viewport)。

我尝试过的事情:

  • 通过使用 enzyme 来规避此问题的shallowdive()而不是mount ,无济于事。
  • 使用 react-media <Media>而不是react-responsive<MediaQuery> ,这似乎设置 window.matchMedia() 默认为 true。然而,这也不起作用。

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

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

最佳答案

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

为不同视口(viewport)创建特定媒体组件:

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>

测试每个视口(viewport)的内容:

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");
    });
});

关于reactjs - 如何测试 react 响应标签内的 react 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51242058/

相关文章:

css - 我似乎无法让我的媒体查询为响应式网站工作

html - 当我的导航栏使用 Twitter Bootstrap 崩溃时,保持我的搜索栏可见

javascript - <head> 使用浏览器打开时不加载脚本

unit-testing - 如何使用 Jest 和 enzyme 测试正在使用其他微前端组件的一个微前端组件

javascript - 测试 (x) 的 CSS 属性值以查看特定媒体查询是否对 JS 等的条件加载有效...

node.js - Express 中中间件测试的 stub 请求\响应

visual-studio - 用于集成 Microsoft 单元测试框架的 CMake (VS2017)

reactjs - 可调整大小的 `antd` 抽屉?

javascript - 如何使用React js在onchange中将数据从一个组件传递到另一个组件

javascript - React - TransitionGroup/ReactCSSTransitionGroup/CSSTransitionGroup 之间有区别吗