Paz Lazar
Paz Lazar

Reputation: 239

Test Mobx inject component

i'm having trouble testing a component with Mobx inject and jest. this is the component:

@inject("mainStore") @observer
export default class TestContainer extends React.Component {
    sum(a, b) {
        return a + b;
    }
    render() {
        return <div className="TestContainer">phhhaz</div>
    }
}

this is a the test:

describe('TestContainer', () => {
it('knows that 2 and 2 make 4', () => {
    const wrapper = shallow(<TestContainer mainStore={{}} />);
    expect(wrapper.instance().sum(2,2)).toBe(4);
});
});

i'm getting this error:

TypeError: wrapper.instance(...).sum is not a function

i know why it's happening but i don't know how to solve it.

Upvotes: 3

Views: 2714

Answers (1)

mweststrate
mweststrate

Reputation: 4978

the problem is that you are shallow rendering the inject component. And since it is a wrapping component (Hoc) you are not testing your own component at all. Instead of rendering and testing TestContainer you should be rendering and testing TestContainer.wrappedComponent. For more details see: https://github.com/mobxjs/mobx-react#testing-store-injection

Upvotes: 3

Related Questions