Monday, November 13, 2017

How to mock babel plugin in Jest test?

Leave a Comment

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?

3 Answers

Answers 1

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); }) 

Answers 2

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.

Answers 3

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}     /> ); 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment