内部<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>
的内容使用 enzyme
与 react-responsive
(或类似的东西,如 react-media
)来处理移动与桌面视口(viewport)。
我尝试过的事情:
- 通过使用
enzyme
来规避此问题的shallow
与dive()
而不是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/