I'm attempting to run Jest tests for a JS file that includes some jQuery. The jQuery code is unrelated and not being tested, but cannot be removed for other reasons. However my test suite will not run because of the jQuery $
. I've been attempting various efforts to either mock or include jQuery somehow in the Jest environment. I'm using webpack's ProvidePlugin
to make jQuery available to all modules in my app and I'm not sure if this is causing issues with $
potentially.
I have the following (psuedo) JS code in myfile.js
:
export const myFunc = () => {
return 'things';
}
// legacy jQuery code which can't be removed
$('.some-element').on('click', doSomethingUnrelated);
I'm intending to test myFunc()
in myfile.test.js
like so:
import { myFunc } from './myfile';
describe('my file', () => {
it('returns things', () => {
// some assertions
})
})
webpack.common.js
:
new webpack.ProvidePlugin({
$: 'jQuery',
jQuery: 'jquery',
...
})
When i run the jest
test like this, it fails with the message: $ is not defined
, which seems fair. Taking some ideas from this Jest issue here: https://github.com/facebook/jest/issues/708 I've tried:
jest.config.js
:
module.exports = {
setupFiles: ['./src/jest-setup-before.js'],
...
}
jest-setup-before.js
:
// window.$ = require('jquery');
//
// import $ from 'jquery'
// global.$ = global.jQuery = $;
//
// global.jQuery = require('jquery');
// global.$ = global.jQuery;
console.log($) // {}
I've also tried the above using setupFilesAfterEnv
instead of setupFiles
to see if installing jquery before tests run would help, but it didn't. These attempts all result in TypeError: $ is not a function
.
I've also tried mocking jquery according to the docs: https://jestjs.io/docs/en/manual-mocks#mocking-node-modules by creating a __mocks__
directory adjacent to node_modules
and creating an empty jquery.js
file. I've also tried in jquery.js
: jest.mock('jquery')
although according to the docs I shouldn't have to.
Just seems like one of those scenarios I'm throwing anything I can at this problem without understanding fully, I'm still pretty new to Jest so any help is greatly appreciated here. Thanks!