简体   繁体   English

开玩笑 TouchEvent TypeError: $ 不是 function

[英]jest TouchEvent TypeError: $ is not a function

I am writing a test for a function MyFuntion and that calls another function sendTouchEvent that instantiates a TouchEvent.我正在为 function MyFuntion编写测试,它调用另一个实例化sendTouchEvent的 function sendTouchEvent。

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:我的 jest.setup.js 文件是这样的:

$ = 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.我已经尝试模拟sendTouchEvent function,但它不起作用。 Also tried to inject $ using rewire mod.__set__ .还尝试使用mod.__set__注入$

Does anyone know how to fix this?有谁知道如何解决这一问题?

I found out that the problem was the rewire lib.我发现问题是rewire库。 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我删除它并更改我的代码以便能够在不rewire的情况下模拟data变量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM