mardi 6 juin 2017

React + Jest how to test changing state in component and checking for another component

React - Test Utilities Docs

I have a Login component which will display a Notification component if this.state.error is true.

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

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);
    });

    it('should render the Notification component if state.error is true', () => {
        // console.log('ReactTestUtils', ReactTestUtils);

        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));

http://ift.tt/1ArDWEa

The render() of my Login component

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>

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

Aucun commentaire:

Enregistrer un commentaire