So I'm testing my React components using Jest & Enzyme, and when I test a component that opens a bootstrap modal, I get the following error:
TypeError: $(...).modal is not a function
makes sense, I haven't references bootstrap at any point yet, so I go ahead and add the following to my jest object in my package.json:
"setupFiles": [
"./app/common/js/jquery-3.1.1.min.js",
"./app/common/js/bootstrap.min.js",
"./__mocks__/beforeTest.js"
]
which then gives me this error:
Bootstrap's JavaScript requires jQuery. jQuery must be included before Bootstrap's JavaScript.
I've set window.$
and global.$
to jQuery to see if that would help my issue, but it doesn't seem to help either, neither does importing the bootstrap module inside my beforeTest.js
file.
I don't need to test the functionality of the modal, I just need the error to go away. So I'm hoping to find a way to load bootstrap such that I can run $(...).modal
. Will bootstrap even work in this environment?
Jest ships with jsdom which simulates a DOM environment as if you were in the browser. This means that every DOM API that we call can be observed in the same way it would be observed in a browser! So we can very easy to simulates a DOM environment when use Jest, get start install Jest and write test case!
beforeAll(fn)Runs a function before any of the tests in this file run. If the function returns a promise, Jest waits for that promise to resolve before running tests. This is often useful if you want to set up some global state that will be used by many tests.
Jest. We use Jest to write frontend unit and integration tests.
This is what helped me:
$.fn.modal = jest.fn();
The mocking will also avoids one to include Bootstrap for test suite.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With