October 30, 2019

How to mock third party libraries and functions in jest using react js


Jest is a library we use for testing JS code whether it's an Angular application or React JS.

Many times we encounter issues while testing code which has third party libraries like mixpanel, moment, redux etc.

To resolve, we need to mock these 3rd party libraries and their respective functions. We need to intercept these libraries by mocking as given below:

1) Create a directory at root as "__mocks__".
2) Let say we need to create mock for moment library. Create a JS file under __mocks__ as moment.js. Keep in mind to have the file name exactly same as declared when importing in source code.
3) Open moment.js file and write below code snippet

const moment = {
  anyFunc: jest.fn()
}
export default moment;

4) Now execute your jest test cases. It will not throw error for moment library.
5) Use can add any mock functions in that file and add expected response and test them.

Hope this helps!

No comments:

Post a Comment