[Create-React-App] Jest 和 Enzyme(3.9.0) 似乎找不到我的 <Button/>
元素来自Auth.jx
容器..
应用程序应呈现 Auth 容器 if(!isAuthernticated)
如果没有提供输入,则应禁用该按钮。
我尝试了ShallowWrapper::dive(),但出现了 TypeError
TypeError: SHallowWrapper::dive() can only be called on components
Auth.jsx
//...
let errorMessage = null;
let button=<Button id='Disabled' btnType="Success" disabled={false}>Disabled</Button>;
let authRedirect = null;
if (this.props.isAuthenticated) {
authRedirect = <Redirect to={this.props.authRedirectPath}/>
}
if (this.state.controls.username.value && this.state.controls.password.value){
button=<Button id='Login' btnType="Success">Login</Button>
}
return (
<div>
{authRedirect}
<form onSubmit={this.handleSubmit}>
{form}
{button}
</form>
</div>
)
}
//...
Auth.test.js
import React from 'react';
import {shallow} from 'enzyme';
import Auth from '../containers/Auth/Auth';
import Button from '../components/Button/button';
import Input from '../components/Input/input';
describe('<Auth/>',() =>{
let wrapper;
beforeEach(()=>{
wrapper=shallow(<Auth authRedirectPath='/' isAuthenticated={false}/>).dive()
})
//Test 1
it('should render disabled button if no input has been specified ',()=>{
expect(wrapper.find(Button).text()).toEqual('Disabled')
});
})
最佳答案
我认为您不应该打电话 dive()
关于wrapper
在你的测试中。相反,您应该浅渲染您的 wrapper
然后调用dive()
或render()
发现Button
测试其文本。
所以,首先:
wrapper = shallow(<Auth authRedirectPath='/' isAuthenticated={false} />)
然后,当您想要find(Button)
时并在渲染时测试其文本,您可以执行以下操作之一:
expect(wrapper.find(Button).dive().text()).toEqual('Disabled')
// OR
expect(wrapper.find(Button).render().text()).toEqual('Disabled')
为了演示这一点,我在 code sandbox 处重新创建了您的代码框架。 .你可以看到,具体在Auth.test.js
我如何用上面的代码行修改您的原始测试。如果单击底部工具栏中的“测试”,您将看到测试通过。
如果您进入 Auth.jsx
然后您更改 username
和password
值 - 从而影响Button
文本 - 那么测试将失败。
关于reactjs - 方法 “text” 应该在 1 个节点上运行。 0 找到代替,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54890326/