Ad

Shallow Does Not Render Wrapped Component

- 1 answer

component.js

<React.Fragment>
{ state.data  ?  jsx :  null }
</React.Fragment>

export default withStyles(styles, { withTheme: true })(Component);

I cannot shallow into a component that is wrapped with withStyles (material-ui styles) and therefore wrapper is returned undefined. I have already tried the dive() method.

My test code looks like this..

Component.test.js

configure ({adapter : new EnzymeAdapter()});
const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);

const setup = (initialState={},props={}) => {
    const store = mockStore(initialState);
    const wrapper = shallow(<Component store={store} {...props}/>).dive();

    return wrapper;
};

const findAttrByTest = (wrapper,val) => {
    return wrapper.find(`[data-test="${val}"]`);
};

describe("renders <Component>", () => {
    let wrapper;
    beforeEach(() => {
        const props = { };
        const initialState = {
                         value: '',
                         id   : ''
                         }
 wrapper = setup(initialState,props);
    });
test("it should return `some text` when no data is loaded", () => {
        const component = findAttrByTest(wrapper,"data-loading");
        expect(component.length).toBe(1);
    });
});

Ad

Answer

By using .WrappedComponent you can access the inner component and remove the dive(). The test code will be like this

configure ({adapter : new EnzymeAdapter()});
const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);

const setup = (initialState={},props={}) => {
    const store = mockStore(initialState);
    const wrapper = shallow(<Component.WrappedComponent store={store} {...props}/>);

    return wrapper;
};

const findAttrByTest = (wrapper,val) => {
    return wrapper.find(`[data-test="${val}"]`);
};

describe("renders <Component>", () => {
    let wrapper;
    beforeEach(() => {
        const props = { };
        const initialState = {
                         value: '',
                         id   : ''
                         }
 wrapper = setup(initialState,props);
    });
test("it should return `some text` when no data is loaded", () => {
        const component = findAttrByTest(wrapper,"data-loading");
        expect(component.length).toBe(1);
    });
});

Ad
source: stackoverflow.com
Ad