mercredi 5 août 2020

Enzyme state-based rendering test issues

I have a react component which I want to test

In the render method I have the next logic:

<div id="someArea">
    {this.renderSection(
        this.state.oneCollection,
        'First:'
    )}
    {this.renderSection(
        this.state.twoCollection,
        'Second:'
    )}
</div>
renderSection = (collection: number[], caption: string) => {
        console.log(collection.length);
        return (collection.length > 0 &&
            <>
                <h6>{caption}</h6>
                ... Collection-related logic ...
            </>);
    }
let wrapper = mount<MyComponent>(<MyComponent
            {...props}
            ...
        />);

        const state: MyComponentState = {
            oneCollection: [
                1
            ],
            twoCollection: [
                2
            ]
        };

        await new Promise(res => {
            wrapper.instance().setState(state, () => {
                res();
            });
        });

        wrapper.instance().render();

        console.log('Test OneCollection length');
        console.log((wrapper.instance().state as MyComponentState).oneCollection.length);
        console.log('Test TwoCollection length');
        console.log((wrapper.instance().state as MyComponentState).twoCollection.length);

        console.log(wrapper.html());

I tried literally everything

.update(), with wrapper re-assignment
.instance().forceUpdate(), .instance().render()
wrapper.setState({})
wrapper.instance().setState({})

that's where I ended

I've read almost every github issue, every SO question which is similar to my problem, tried everything listed there But no success

The main point is when I log state properties in the test - it outputs right values But when I log state properties inside render method - it outputs wrong values

Seems like state is simply ignored by rendering inside enzyme

How can it be solved?

Aucun commentaire:

Enregistrer un commentaire