reactjs - 方法 “text” 应该在 1 个节点上运行。 0 找到代替

标签 reactjs unit-testing tdd jestjs babel-jest

enter image description here

[Create-React-App] JestEnzyme(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然后您更改 usernamepassword值 - 从而影响Button文本 - 那么测试将失败。

关于reactjs - 方法 “text” 应该在 1 个节点上运行。 0 找到代替,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54890326/

相关文章:

javascript - then()方法在react中实际返回数据之前执行

java - Junit 最佳实践 : Public method calling multiple private methods

unit-testing - 如何在另一个方法中 stub

version-control - 重构和源代码控制 : How To?

javascript - 使用 Formik 编辑条目,Yup 无法识别现有字段

html - 右侧滚动导航栏透明?

Scala 单元测试标准输入/标准输出

c# - 第一个没有断言/预期异常的 TDD 测试。这值得么?

django - 我如何对 Django URL 进行单元测试?

javascript - react backgroundImage 内联样式不起作用