【发布时间】:2018-06-21 05:52:42
【问题描述】:
问题:
我正在尝试在 ES6 中测试 React 无状态组件的点击功能。但是,当使用 sinon 监视 handleClick 函数时,我得到了响应...
TypeError: Cannot read property 'goToFullCart' of undefined
我尝试了其他一些方法。当组件是 Class 组件时,其中一些似乎可以工作,但在使用无状态功能组件时,所有方法似乎都失败了,如下所示...
代码:
import React from 'react'
import PropTypes from 'prop-types'
import SVG from '../../../../static/svg/Svg';
import Svgs from '../../../../static/svg/SvgTemplates';
const TestComponent = ({order, router}) => {
const handleClick = (event) => {
event.stopPropagation()
router.push(`/order/${order.orderId}/cart`);
}
return (
<button className="preview-bar" onClick={handleClick}>
<p>Button Content</p>
</button>
)
}
TestComponent.propTypes = {
order: PropTypes.object.isRequired,
router: PropTypes.object.isRequired,
}
export default TestComponent
export { TestComponent }
import React from 'react';
import { shallow, mount } from 'enzyme';
import { expect } from 'chai';
import sinon from 'sinon';
import TestComponent from "./TestComponent"
let wrapper, props;
describe('<TestComponent /> component unit tests', () => {
describe('when the minimized cart is clicked', () => {
beforeEach(function() {
props = {
}
wrapper = shallow((<TestComponent {...props} />))
});
it('should have a goToFullCart method', () => {
const spy = sinon.spy(TestComponent.prototype, 'handleClick');
expect(spy).to.equal(true)
});
});
});
我不知道如何监视 handleClick 方法以检查何时单击按钮。
感谢您的帮助和讨论。如果有任何不清楚的地方,请随时要求澄清。
干杯
【问题讨论】:
标签: javascript reactjs unit-testing ecmascript-6 sinon