【问题标题】:redux dumb component function unit-testredux 哑组件功能单元测试
【发布时间】:2017-03-05 10:56:12
【问题描述】:

我对智能/哑组件等非常熟悉。现在我正在做类似的事情

LoginContainer 通过 mapStateToProps 和 mapDispatchToProps 使用 react-redux 与 redux 连接。

然后我有一个包含 UI 和内容的 LoginComponent。

所以问题是,当用户单击“LoginComponent”中的登录按钮时,它必须在那里调用一个函数。所以我猜的方法是从LoginContainer传递函数,然后在LoginComponent中点击按钮时调用它?

但是这样一来,是不是意味着在做单元测试的时候,我必须在哑组件LoginComponent中模拟这个按钮函数调用的功能?

【问题讨论】:

    标签: javascript reactjs redux react-redux


    【解决方案1】:

    我认为你是完全正确的。 LoginContainer 组件需要提供您希望在用户单击登录按钮时执行的功能。看我的例子:

    LoginContainer

    import { connect } from 'react-redux'
    
    import Login from '../components/login'
    import { initiateLoginRequest } from '../actions/login'
    
    const LoginContainer = connect(null, { initiateLoginRequest })(Login)
    
    export default LoginContainer
    

    注意:我提供了一个对象作为connect() 的第二个参数,而不是一个函数。您可以在 redux 文档中了解这一点。

    所以现在我的登录组件可以利用传入的函数来调度一个动作:

    <Button
        raised
        primary
        label="Login"
        onClick={this.props.initiateLoginRequest()}
    />
    

    这个按钮将存在于我的组件render() 方法中的某个位置。

    如果您想测试这样的演示组件,我建议您查看Enzyme。 Enzyme 是一个用于 React 的 JavaScript 测试实用程序,它允许您编写如下测试:

    import expect from 'expect'
    import React from 'react'
    import { shallow } from 'enzyme'
    import { Button } from 'react-toolbox/lib/button'
    
    import Login from '../../src/components/login'
    
    function setup() {
      const props = {
        initiateLoginRequest: expect.createSpy()
      }
    
      const wrapper = shallow(<Login {...props} />)
    
      return {
        props,
        wrapper
      }
    }
    
    describe('components', () => {
      describe('Login', () => {
        describe('Login Button', () => {
          it('should dispatch the proper action ', () => {
            const { wrapper, props } = setup()
            expect(props.initiateLoginRequest.calls.length).toBe(0)
            wrapper.find(Button).at(1).simulate('click')
            expect(props.initiateLoginRequest.calls.length).toBe(1)
          })
        })
      })
    })
    

    基本上你创建一个间谍,通过它的道具将它传递给组件,然后模拟一个点击事件。然后,您可以在测试中检查该方法是否已被实际调用。

    【讨论】:

      猜你喜欢
      • 2017-08-29
      • 2021-08-18
      • 2020-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-01
      • 2021-09-07
      • 1970-01-01
      相关资源
      最近更新 更多