【问题标题】:Testing - React stateless components, spying on component methods using sinon测试 - 反应无状态组件,使用 sinon 监视组件方法
【发布时间】: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


    【解决方案1】:

    无状态组件基本上是一个函数。最好不要在其中创建另一个函数,因为它会创建一个闭包,如果您想在组件内创建方法,请创建有状态组件

    您可以测试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);
    });
    

    希望对您有所帮助!

    【讨论】:

    • 我不同意这句话:“最好不要在其中创建另一个函数,因为它会创建一个闭包”我们在 react 文档中看到的带有钩子的示例也不同意跨度>
    • 使用最新的 react hooks 我们可以使用函数式组件代替类组件,因此需要组件的测试方法,如果有人找到了答案,请告诉我们。谢谢
    猜你喜欢
    • 2018-07-18
    • 2017-11-30
    • 2021-04-18
    • 2018-08-20
    • 1970-01-01
    • 2019-03-08
    • 2018-07-01
    • 2023-03-27
    • 2019-05-20
    相关资源
    最近更新 更多