Skip to content

Instantly share code, notes, and snippets.

@elvisgiv
Last active July 2, 2019 14:04
Show Gist options
  • Save elvisgiv/85623b613bbf2ce46e49d9c5c0677a0a to your computer and use it in GitHub Desktop.
Save elvisgiv/85623b613bbf2ce46e49d9c5c0677a0a to your computer and use it in GitHub Desktop.

enzyme, mocha, chai testing changes in STATE of component

we have LogsList.js component

import React from 'react'

export default class LogsList extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            sortDate: -1,
        };
        this.reset = this.reset.bind(this);
    }
    reset() {
        this.setState({sortDate: null});
    };

    render() {
        return (
            <div>
                <Button onClick={() => this.reset()}>
                    Clear
                </Button>
    }
}

in LogsList.spec.js

import React from 'react';
import {mount} from 'enzyme';
import {expect} from 'chai';
import LogsList from '../src/components/page_components/logs/LogsList';
import {Router} from "react-router";
import {createBrowserHistory} from "history";
const history = createBrowserHistory();
//
const wrapper = mount(
    <Router history={history}>
        <LogsList/>
    </Router>
);

describe('<LogsList/>', function () {

    it('Click on button "button". state.sortDate should be changed ', function () {
        // to get state from component with instance help
        const componentInstance = wrapper
            .childAt(0) // could also be .find(Foo)
            .instance();
        console.log('componentInstance before click', componentInstance.state);
        // do testing with componentInstance.state.something or componentInstance.props.something
        wrapper.find('button').simulate('click');
        console.log('componentInstance after click', componentInstance.state);
        //
        expect(componentInstance.state.sortDate).to.equal(null);
    });

});

see enzymejs/enzyme#431 (comment)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment