Reputation: 157
Suppose I have a component which is wrapped in Material-UI's withWidth HOC. How do you mock withWidth's isWidthUp function using jest to return a predetermined bool?
SUT
import React, { Component } from 'react';
import withWidth, { isWidthUp } from '@material-ui/core/withWidth';
class ComponentWithWidth extends Component {
render() {
const { width } = this.props;
return isWidthUp('md', width)
? <p>above md</p>
: <p>below md</p>;
}
}
export default withWidth()(ComponentWithWidth);
What I have tried
Attempt 1
import React from 'react';
import { configure, mount } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import ComponentWithWidth from '../ComponentWithWidth';
import { isWidthUp } from '@material-ui/core/withWidth';
configure({ adapter: new Adapter() });
jest.mock('@material-ui/core/withWidth');
describe('ComponentWithWidth', () => {
it('Should render', () => {
isWidthUp = jest.fn().mockReturnValue(true);
const el = mount(<ComponentWithWidth />);
});
});
Problem
TypeError: (0 , _withWidth.default)(...) is not a function
Attempt 2
import React from 'react';
import { configure, mount } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import ComponentWithWidth from '../ComponentWithWidth';
import withWidth from '@material-ui/core/withWidth';
configure({ adapter: new Adapter() });
describe('ComponentWithWidth', () => {
it('Should render', () => {
withWidth.isWidthUp = jest.fn().mockReturnValue(false);
const el = mount(<ComponentWithWidth />);
});
});
Problem
The component disregards the widthWidth.isWidthUp mock return value.
Upvotes: 3
Views: 1349
Reputation: 3594
I'm not familiar with esmodules mocking but I do think that you should not test it this way (testing implementation details that is).
You could simply pass the width
prop in the mount which is basically mocking. See demo.test.js
: https://codesandbox.io/s/m9o783rox
Upvotes: 2