我认为你是完全正确的。 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)
})
})
})
})
基本上你创建一个间谍,通过它的道具将它传递给组件,然后模拟一个点击事件。然后,您可以在测试中检查该方法是否已被实际调用。