Reputation: 3002
I am using a babel plugin which provides a function called myHelper
which is used (but not imported since it is provided as a babel plugin) inside a component I want to test.
How do I "globally" mock myHelper
with Jest?
Upvotes: 0
Views: 502
Reputation: 10419
I would let those components accept a myHelper
property to optionally mock myHelper
method provided by babel. By default the property would point to the original myHelper
method:
class MyComponent extends Component {
constructor() {
// Use myHelper function like:
this.props.myHelper();
}
return (
<div>...</div>
);
}
MyComponent.propTypes = {
myHelper: PropTypes.func.isRequired,
};
MyComponent.defaultProps = {
// set by default to babel-provided method
myHelper: myHelper,
};
..and that in your tests using, for example, enzyme:
const myHelperMock = jest.fn();
const wrapper = shallow(
<MyComponent
myHelper={myHelperMock}
/>
);
Upvotes: 1
Reputation: 2032
I see two directions where yo could go :
- make the helper available globally and test how your code interacts with it
- make the helper available through a babel-jest
and write your tests accordingly
The first one can be achieved using the setupFiles
field in the jest configuration : it lets you specify an array of scripts to be executed before your tests are run. You can make your helper globally in one of those.
The second one can be achieved by specifying a transform
in the jest config. Something like
"transform": {
"^.+\\.(js|jsx)$": "<rootDir>/node_modules/babel-jest"
}
Feel free to comment if your request is more specific.
Upvotes: 0
Reputation: 1114
It might be bad manner, it is possible by making myHelper
to global.
// myHelper.js
function myHelper(){
return work() // expected 1
}
if (global) {
global.myHelperFunction = myHelper;
}
// myHelper.test.js
test('TEST MY HELPER', () => {
expect(global.myHelperFunction()).toBe(1);
})
Upvotes: 0