I am writing a test for a function MyFuntion
and that calls another function sendTouchEvent
that instantiates a TouchEvent.
function sendTouchEvent(element, eventType) {
const touch = new Touch({
...
});
const touchEvent = new TouchEvent(eventType, {
...
});
element.dispatchEvent(touchEvent);
}
My test is like this:
const { test, expect } = require("@jest/globals");
const fs = require('fs');
const chrome = require("sinon-chrome");
const { JSDOM } = require("jsdom");
const dom = new JSDOM()
global.document = dom.window.document
global.window = dom.window
global.chrome = chrome
global.MutationObserver = class {
constructor(callback) {}
disconnect() {}
observe(element, initObject) {}
};
jest.dontMock('jquery');
$ = jQuery = require("jquery");
global.$ = $
global.jQuery = jQuery
const content = require("../content");
const data = require("./fixtures/data.json");
test("get data", () => {
const mod = rewire("../content")
mod.__set__('data', data) // mocking json data
var el = document.createElement("div")
el.innerHTML = html_str; // loaded before with fs.readFileSync
expect(content.MyFunction(el)).toBe({})
})
My jest.setup.js file is like this:
$ = require("jquery");
global.$ = $;
global.window.$ = $;
And I am getting this error:
TypeError: $ is not a function
207 | });
208 |
> 209 | const touchEvent = new TouchEvent(eventType, {
| ^
210 | cancelable: true,
211 | bubbles: true,
212 | touches: [touch],
at extension/content.js:209:48
at Object.<anonymous> (extension/content.js:411:4)
at Object.load (node_modules/rewire/lib/moduleEnv.js:55:18)
at internalRewire (node_modules/rewire/lib/rewire.js:49:15)
at rewire (node_modules/rewire/lib/index.js:11:12)
at Object.<anonymous> (extension/tests/content.test.js:26:17)
I tried to mock the sendTouchEvent
function already, but it doesn't work. Also tried to inject $
using rewire mod.__set__
.
Does anyone know how to fix this?
I found out that the problem was the rewire
lib. For some reason, it was messing with the window's events. I remove it and change my code to be able to mock data
variable without rewire
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