I get this error trying to run test for my Jquery code
TypeError: Cannot read properties of undefined (reading 'css')
20 |
21 | export const alertError = (message, errorclass) => {
> 22 | $(`.${errorclass}`).css("display", "block");
| ^
23 | $(`.${errorclass}`).html(`
24 | <div class="alert alert-icon alert-error alert-bg alert-inline">
25 | <h4 class="alert-title">
at alertError (static/js/utils/alert.js:22:22)
at getUserChatrooms (static/js/modules/chat/chat_ajax.js:29:19)
at Object.<anonymous> (static/js/modules/chat/tests/chat_ajax.spec.js:38:45)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 5 passed, 6 total
My current mocks/jquery.js
import $ from 'jquery';
// Mock jQuery and attach it to the global object
global.$ = $;
global.jQuery = $;
// Turn off jQuery animations
jQuery.fx.off = true;
// Mock specific jQuery instances
$.fn.extend = jest.fn();
$.ajax = jest.fn();
$.fn = {
on: jest.fn().mockReturnThis(),
children: jest.fn().mockReturnThis(),
attr: jest.fn().mockReturnThis(),
css: jest.fn().mockReturnThis(),
html: jest.fn().mockReturnThis(),
};
$.document = $();
$.document.body = $();
How do I fix this? I can’t think of a way to fix it without having to mock the alert.js functions.