我正在尝试对包含来自库 https://react.semantic-ui.com/ 的带有按钮的表单的登录组件进行单元测试。 ,组件是这样的:
<LoginComponent onSubmit={onSubmit} data={req.data} />
我现在的测试是这样的:
import React from 'react';
import { mount, configure } from 'enzyme';
import { Button } from 'semantic-ui-react';
import LoginComponent from './LoginComponent';
import Adapter from 'enzyme-adapter-react-16';
configure({adapter: new Adapter()});
it('Email check', () => {
const wrapper = mount(<LoginComponent data={undefined} onSubmit={ console.log("submitted" }/>);
console.log(wrapper.find(Button));
})
控制台日志返回 ReactWrapper {} 编辑
这里是 loginComponent 的源代码:
import React, {useEffect} from 'react'
import useForm from 'react-hook-form'
import { Grid, Message, Card, Input, Button, Form, Image } from 'semantic-ui-react'
import { REGEX_EMAIL_VALIDATION, ERROR_LOGIN_INVALID } from '../common/consts';
import './login.css'
const LoginComponent = props => {
const { register, handleSubmit, setValue } = useForm();
const handleFormChange = type => event => {
setValue(type, event.target.value)
}
useEffect(()=> {
register({name: 'email'}, {required: true, pattern: REGEX_EMAIL_VALIDATION})
register({name: 'password'}, {required: true, min: 6})
}, [register])
return(
<Grid centered columns={4} verticalAlign='middle' className="h-100">
<Grid.Row>
<Grid.Column textAlign="center" >
<Card centered fluid raised={true} className='card-login'>
<Card.Content>
<Image src='img/logo.png' size='small' className='pa4'/>
{ props.data !== undefined ? 'AuthError' in props.data && (
<Message negative>
<Message.Header>{ERROR_LOGIN_INVALID}</Message.Header>
</Message>
)
: null
}
<Form onSubmit={handleSubmit(props.onSubmit)} className='pt3'>
<Form.Field>
<Input icon='user' type="email" name="email" placeholder="Correo Electronico"
className='login-input' size="big" onChange={handleFormChange('email')} />
</Form.Field>
<Form.Field>
<Input icon='lock' type="password" name="password" placeholder="Contraseña"
className='login-input'size="big" onChange={handleFormChange('password')} />
</Form.Field>
<Form.Field className='pt3'>
<Button fluid type='submit' content='Iniciar Sesión' size="big" className='login-button' id="suh"/>
</Form.Field>
</Form>
</Card.Content>
</Card>
</Grid.Column>
</Grid.Row>
</Grid>
)
}
export default LoginComponent;
最佳答案
这是正常的;无论是否找到元素,您通常都会得到 ReactWrapper {}
。尝试 console.log(wrapper.find(Button).length);
查看是否找到匹配的元素/组件。如果是这样,您可以执行 console.log(wrapper.find(Button).debug());
来查看其内容。
关于reactjs - enzyme 发现无法在已经变浅的组件中找到组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57779778/