joe*_*joe 20 javascript unit-testing reactjs jestjs enzyme
所以基本上当组件安装时,我有一个事件监听器监听resize事件.它切换isMobileView状态,然后将其作为道具传递给子项.因此,这是必要的,这是有效的,并经过测试.我是一个相当新的测试人员,我正试图找出一种方法,我可以编写一个测试来调整窗口大小并使所有逻辑发生并测试它是如何执行的.
这是代码 -
componentDidMount() {
this.setMobileViewState()
window.addEventListener('resize', this.setMobileViewState.bind(this));
}
setMobileViewState() {
if(document.documentElement.clientWidth <= this.props.mobileMenuShowWidth) {
this.setState({ isMobileView: true })
} else {
this.setState({ isMobileView: false })
}
}
Run Code Online (Sandbox Code Playgroud)
我知道代码有效,但我想为它编写一个测试.基本上只是确保状态正确变化的东西.
Joe*_*dee 28
使用Jest和Enzyme,您可以执行以下操作.Jest已经完成了JSDOM.在你的测试中,Jest提供了window对象,它由global(我认为window.innerWidthJest 的默认设置为1024px)表示:
test('Test something when the viewport changes.', () => {
// Mount the component to test.
const component = mount(<ComponentToTest/>);
...
// Change the viewport to 500px.
global.innerWidth = 500;
// Trigger the window resize event.
global.dispatchEvent(new Event('resize'));
...
// Run your assertion.
});
Run Code Online (Sandbox Code Playgroud)
小智 10
如果您收到打字稿错误消息
无法分配给“ innerWidth”,因为它是只读属性。
尝试:
Object.defineProperty(window, 'innerWidth', {writable: true, configurable: true, value: 200})
Run Code Online (Sandbox Code Playgroud)
试试这一行:
window = Object.assign(window, { innerWidth: 500 });
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16656 次 |
| 最近记录: |