Skip to content

Instantly share code, notes, and snippets.

@elvisgiv
Created July 3, 2019 08:42
Show Gist options
  • Save elvisgiv/e9056bde1cfbf5bcfecdfb32c10577ea to your computer and use it in GitHub Desktop.
Save elvisgiv/e9056bde1cfbf5bcfecdfb32c10577ea to your computer and use it in GitHub Desktop.

enzyme setState example

we have ItemsList.js component with state

import React from 'react'

export default class ItemsList extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            loaded: false,
            itemsList: []

        };
    }

    render() {
        if (!this.state.loaded) {
            return (
                <LinearProgress determinate={false}/>
            )
        }
        let items = this.state.itemsList;
        if (items.length === 0) {
            return (
                <h6 className="padd-left-md">No Items found</h6>
            )
        }        
        return (
            <div>
                <input />
                some code when {loaded: true} and _this.state.itemsList > 0_
            </div>
    }
}

to test some code in this component we should change the state in ItemsList.spec.js

import React from 'react';
import {mount} from 'enzyme';
import {expect} from 'chai';

import ItemsList from '../src/components/page_components/ItemsList';

import {Router} from "react-router";
import {createBrowserHistory} from "history";
// for TypeError: window.requestAnimationFrame is not a function
import 'raf/polyfill';

const history = createBrowserHistory();

const itemsStub = [{
    some item things
}];

const wrapper = mount(
    <Router history={history}>
        <ItemsList />
    </Router>
);
// this is for work a setState in enzym
const componentInstance = wrapper
    .childAt(0) // could also be .find(Foo)
    .instance();


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

    it('should have an "LinearProgress"', function () {
        expect(wrapper.find("LinearProgress")).to.have.lengthOf(1);
    });

    it('should have an "No Items found"', function () {
        componentInstance.setState({loaded: true});
        wrapper.update();
        expect(wrapper.find(".padd-left-md")).to.have.lengthOf(1);
        expect(wrapper.find(".padd-left-md").props().children).to.equal('No Items found');
    });

    it('should have an "input"', function () {
        componentInstance.setState({loaded: true, itemsList: itemsStub});
        wrapper.update();
        // console.log('debug', wrapper.debug());
        expect(wrapper.find("input")).to.have.lengthOf(1);
    });

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