Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing bootstrap functionality in Jest testing

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?

like image 592
westbyb Avatar asked Jul 20 '17 21:07

westbyb


People also ask

How is Dom testing with Jest?

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!

What is Jest beforeAll?

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.

Is Jest for front end testing?

Jest. We use Jest to write frontend unit and integration tests.


1 Answers

This is what helped me:

$.fn.modal = jest.fn();

The mocking will also avoids one to include Bootstrap for test suite.

like image 152
kks1 Avatar answered Sep 23 '22 00:09

kks1