我非常熟悉智能/哑组件等。现在我在做一些像
LoginContainer通过mapStateToProps和mapDispatchToProps使用react-redux与redux连接。
然后我有一个LoginComponent,它有UI和其他东西。
所以问题是,当用户单击“登录组件”中的登录按钮时,它必须调用那里的函数。所以,我猜方法是从LoginContainer传递函数,然后在LoginComponent中单击按钮时调用它?
但是这样,这是否意味着在进行单元测试时,我必须在愚蠢的组件LoginComponent中模拟这个按钮函数调用的功能?
我认为你完全正确。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
注意:我提供了一个对象作为第二个参数连接()
而不是函数。你可以在redux文档中读到这一点。
现在,我的登录组件可以利用传入的函数来分派操作:
<Button
raised
primary
label="Login"
onClick={this.props.initiateLoginRequest()}
/>
这个按钮将位于我的组件渲染()
方法中的某个地方。
如果你想测试这样一种表现成分,我建议你看看酶。Ezyme是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)
})
})
})
})
基本上,您可以创建一个间谍,通过其道具将其传递给组件,然后模拟单击事件。然后,您可以在测试中检查该方法是否已被实际调用。