javascript - 未模拟的方法的开玩笑测试调用
问题描述
我有一个 React 组件MyComponent
,我想在其中测试用户旋转手机时应该触发的行为。
组件内部:
export class MyComponent extends React.PureComponent<props> {
componentDidMount() {
window.addEventListener('orientationchange', this.onRotation)
}
componentWillUnmount() {
window.removeEventListener('orientationchange', this.onRotation)
}
onRotation = () => {
// do things
}
render() {
// ...
}
}
我在 medium 上找到了一篇文章,描述了如何为此编写测试。但是,这对我不起作用。
describe('<MyComponent />', () => {
it('does things on rotation', () => {
const map : any = {}
window.addEventListener = jest.fn((event, cb) => {
map[event] = cb;
})
const wrapper : any = mount(<MyComponent />)
map.orientationchange()
expect(wrapper.onRotation).toHaveBeenCalled()
})
})
在文章中这有效,但是我收到一个错误:
"Matcher error: received value must be a mock or spy function
Received has value: undefined"
使用间谍也不起作用:
it('does things on rotation', () => {
const map : any = {}
window.addEventListener = jest.fn((event, cb) => {
map[event] = cb;
})
const wrapper : any = mount(<MyComponent />)
const spy = jest.spyOn(wrapper.instance(), 'onRotation')
map.orientationchange()
expect(spy).toHaveBeenCalled()
})
它说:
"Expected mock function to have been called, but it was not called."
解决方案
监视 onRotation 中的函数。
import React from 'react';
class OrientationChange extends React.Component {
componentDidMount() {
window.addEventListener('orientationchange', this.onRotation)
}
componentWillUnmount() {
window.removeEventListener('orientationchange', this.onRotation)
}
handleRotation = () => {
console.log('inside handle rotation');
}
onRotation = (event) => {
this.handleRotation()
}
render() {
return (
<div>Testing</div>
)
}
}
export default OrientationChange;
describe('<OrientationChange /> orientation change test', () => {
it('does things on rotation', () => {
const map = {}
window.addEventListener = jest.fn((event, cb) => {
map[event] = cb;
})
const wrapper = mount(<OrientationChange />)
const spy = jest.spyOn(wrapper.instance(), 'handleRotation')
map.orientationchange();
expect(spy).toHaveBeenCalled()
})
})
推荐阅读
- android-studio - 错误:包android.support.v4.content不存在导入android.support.v4.content.FileProvider;
- python - 在 Bokeh 仪表板中使用 Python 进行 K-means 聚类;创建一个表来显示集群的意思
- flutter - 类型“ASN1Object”不是类型转换中“ASN1Sequence”类型的子类型
- reactjs - 功能组件中局部变量的最佳方式反应原生
- python - 使用正则表达式从 ifConfig 获取 MAC 地址
- windows - 如何让 Windows 程序监听来自 WSL 的连接而不绑定到 0.0.0.0?
- javascript - 响应式移动导航栏链接无法在移动设备上运行
- django - 在 Django 中:即使在 forms.py 中使用“queryset = objects.none()”后,我仍然可以看到包含所有选项的下拉菜单
- java - 如何添加第二个css选择器xpath,其中相同的元素出现多次
- python - 无法使用 conda 安装 m2w64-libpng