Javascript React & Jest,如何测试改变状态并检查另一个组件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44399181/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:29:43  来源:igfitidea点击:

React & Jest, how to test changing state and checking for another component

javascriptreactjstestingjestjs

提问by Leon Gaban

React - Test Utilities Docs

React - 测试工具文档

I have a Logincomponent which will display a Notificationcomponent if this.state.erroris true.

我有一个登录组件,如果为真,它将显示一个通知组件this.state.error

I'm now writing a Jest test to test this.

我现在正在编写一个 Jest 测试来测试这个。

import React from 'react'
import ReactTestUtils from 'react-dom/test-utils';
import { shallow } from 'enzyme'
import toJson from 'enzyme-to-json'
import Login from './Login'
import Notification from '../common/Notification'

describe('<Login /> component', () => {
    it('should render', () => {
        const loginComponent = shallow(<Login />);
        const tree = toJson(loginComponent);
        expect(tree).toMatchSnapshot();
    });

    it('should contains the words "Forgot Password"', () => {
        const loginComponent = shallow(<Login />);
        expect(loginComponent.contains('Forgot Password')).toBe(true);
    });

    // This test fails
    it('should render the Notification component if state.error is true', () => {
        const loginComponent = ReactTestUtils.renderIntoDocument(
            <Login />
        );

        const notificationComponent = ReactTestUtils.renderIntoDocument(
            <Notification />
        );

        loginComponent.setState({
            error: true
        }, expect(ReactTestUtils.isDOMComponent(notificationComponent)).toBe(true));
    });
});

However currently the test is failing, and I'm not sure why

但是目前测试失败,我不知道为什么

enter image description here

在此处输入图片说明

In the last part of my code I've also tried this to no avail

在我的代码的最后一部分我也试过这个无济于事

loginComponent.setState({
        error: true
    }, expect(ReactTestUtils. isElement(notificationComponent)).toBe(true));

https://facebook.github.io/react/docs/test-utils.html

https://facebook.github.io/react/docs/test-utils.html

The render() of my Login component

我的 Login 组件的 render()

render() {
    const usernameError = this.state.username.error;
    const error = this.state.error;
    const errorMsg = this.state.errorMsg;

    return (
        <div className="app-bg">
            { error &&
                <Notification message={ errorMsg } closeMsg={ this.closeMessage }/>
            }
            <section id="auth-section">
                <header>
                    <img src="static/imgs/logo.png"/>
                    <h1>tagline</h1>
                </header>

Also tried this method for testing for the Notification component after setting state.error to true

在将 state.error 设置为 true 后,也尝试了这种方法来测试 Notification 组件

it('should render the Notification component if state.error is true', () => {
    const loginComponent = ReactTestUtils.renderIntoDocument(
        <Login />
    );

    const notificationComponent = ReactTestUtils.renderIntoDocument(
        <Notification />
    );

    // loginComponent.setState({
    //  error: true
    // }, expect(ReactTestUtils.isDOMComponent(notificationComponent)).toBe(true));

    const checkForNotification = () => {
        const login = shallow(<Login />);
        expect(login.find(Notification).length).toBe(1);
    };

    loginComponent.setState({
        error: true
    }, checkForNotification());
});

But that test also failed.

但那个测试也失败了。

Also tried const login = mount(<Login />);

也试过 const login = mount(<Login />);



Anyone else running into a problem using Jest and the React Test Utilities?

还有其他人在使用 Jest 和 React Test Utilities 时遇到问题吗?

回答by Leon Gaban

Figured it out! Did not need React Test Utilities

弄清楚了!不需要React 测试工具

it('should render the Notification component if state.error is true', () => {
    const loginComponent = shallow(<Login />);
    loginComponent.setState({ error: true });
    expect(loginComponent.find(Notification).length).toBe(1);
});

This will set the state of error to true in the Logincomponent, then check if the Logincomponent contains the Notificationcomponent.

这将在Login组件中将错误状态设置为 true ,然后检查Login组件是否包含Notification组件。

回答by Swivel

This should probably be refactored a bit. The Notificationcomponent should probably be alwaysrendered in a more global component (like a Page Wrapper or some sort of other container), and it should probably render nullunless there's errors within a global reducer. A Logincomponent probably shouldn't maintain the responsibility and business logic regarding notifications.

这可能应该重构一下。该Notification组件可能应该始终在更全局的组件中呈现(如 Page Wrapper 或某种其他容器),并且它可能应该呈现,null除非全局减速器中存在错误。一个Login组件可能不应该维持关于通知的责任和业务逻辑。