所以我搜索了一个答案,但还没找到一个适合我用例的答案。我对使用Jest / Enzyme进行测试有点新,对于重构测试非常新。
我不知道如何测试我的功能组件,它是使用重构创建的。我似乎无法弄清楚如何在我的测试中访问道具(状态和处理函数)。
以下是我的功能组件的示例,我将调用 UserDetails
const UserDetails = ({
userInfo,
onUserInfoUpdate,
className,
error,
title,
primaryBtnTitle,
submit,
secondaryBtnTitle,
secondaryBtnFunc,
...props
}) => (
<div className={className}>
<div className="user-details-body">
<Section title="User details">
<TextInput
caption="First Name"
value={userInfo.first}
onChange={onUserInfoUpdate('first')}
name="first-name"
min="1"
max="30"
autoComplete="first-name"
/>
<TextInput
caption="Last Name"
value={userInfo.last}
onChange={onUserInfoUpdate('last')}
name="last-name"
min="1"
max="30"
autoComplete="last-name"
/>
</Section>
</div>
<div className="errorBar">
{error && <Alert type="danger">{error}</Alert>}
</div>
<ActionBar>
<ButtonGroup>
<Button type="secondary" onClick={secondaryBtnFunc}>
{secondaryBtnTitle}
</Button>
<Button type="primary" onClick={submit}>
{primaryBtnTitle}
</Button>
</ButtonGroup>
</ActionBar>
</div>
以下是我的 index.js 文件的示例代码,该文件将我的withState和withHandlers组合到我的Component:
import UserDetails from './UserDetails'
import { withState, withHandlers, compose } from 'recompose'
export default compose(
withState('error', 'updateError', ''),
withState('userInfo', 'updateUserInfo', {
first: '',
last: '',
}),
withHandlers({
onUserInfoUpdate: ({ userInfo, updateUserInfo }) => key => e => {
e.preventDefault()
updateCardInfo({
...cardInfo,
[key]: e.target.value,
})
},
submit: ({ userInfo, submitUserInfo }) => key => e => {
e.preventDefault()
submitUserInfo(userInfo)
//submitUserInfo is a graphQL mutation
})
}
})
)
现在我正在尝试为这个组件编写测试。我导入包含Component的索引文件以创建HOC。
import React from 'react'
import renderer from 'react-test-renderer'
import { mount, shallow } from 'enzyme'
import UserDetails from './'
describe('UserDetails Element', () => {
it('test', () => {
const tree = mount( <UserDetails /> )
console.log(tree.props());
})
})
控制台日志在终端
中给我这个{ children:
{ '$$typeof': Symbol(react.element),
type:
{ [Function: WithState]
displayName: 'withState(withState(withHandlers((UserDetails)))))' },
key: null,
ref: null,
props: {},
_owner: null,
_store: {} } }
如果我是console.log tree.props('userInfo')
,我会得到相同的输出。如果我是console.log tree.prop('userInfo')
或tree.props().userInfo
此外,当我尝试在测试文件中使用我的处理程序时,我收到一个错误,该方法未定义。
我哪里错了?的谢谢!
答案 0 :(得分:0)
您的测试会加载增强型组件,而不是基础裸 UserDetails
组件。所以你用console.log
看到的是最外层组件(compose
)的道具。您可以使用tree.find(UserDetails)
获取内部组件。
为此,您必须在测试中导入两个文件:
import UserDetails from './'
import BareUserDetails from './UserDetails'
以这种方式和find
const tree = mount( <UserDetails /> )
const innerDetails = tree.find(BareUserDetails);
enzyme
的{{1}}并不总能找到您想要的方式。试验find
提供的各种选项。