问题:
我正在尝试在ES6中测试React无状态组件的点击功能。但是,当使用 sinon 监视 handleClick 函数时,我得到了响应...
TypeError: Cannot read property 'goToFullCart' of undefined
我尝试过一些其他方法。当组件是类组件时,其中一些方法似乎可以工作,但当使用无状态功能组件时,所有方法似乎都会失败,如下所示......
代码:
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 方法来检查按钮何时被单击。
感谢您的帮助和讨论。如果有任何不清楚的地方,请随时要求澄清。
干杯
最佳答案
无状态组件基本上是一个函数。好的做法是不要在其中创建另一个函数,因为它会创建一个闭包,如果您想在组件内部创建方法,请创建有状态组件
您可以测试 route
是否更改,而不是测试 handleClick
import React from 'react';
import {shallow} from 'enzyme';
test('should call handleClick method when button got clicked', () => {
window.location.assign = mock;
wrapper .find('button').simulate('click');
expect(window.location.assign).toHaveBeenCalled(1);
});
希望这对您有帮助!
关于javascript - 测试 - React 无状态组件,使用 sinon 监视组件方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48214893/