使用jQuery进行组件响应而不需要-开玩笑的单元测试 [英] React component using jQuery without require - jest unit tests

查看:551
本文介绍了使用jQuery进行组件响应而不需要-开玩笑的单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的React mixin,它使用jQuery触发事件

I have a very simple React mixin which uses jQuery to trigger an event

MyMixin = {
  trackStructEvent: function () {
    args = Array.prototype.slice.call(arguments);
    $('body').trigger('myEvent', args);
  }
module.exports = MyMixin

使用浏览器将其作为一组新组件的一部分导入到主站点中.由于拥有这些组件的主要站点将始终包含jQuery,因此,我不想使用带有browserify的jQuery,因为它将被复制.

This is imported into the main site as part of a new set of components using browserify. As the main site holding these components will always include jQuery, I don't want to require jQuery with browserify, as it will be duplicated.

就行为而言,这不是问题-但是,在运行笑话以使用此mixin引发错误对组件进行单元测试时,会引起问题.

This isn't an issue in terms of behaviour - however it causes problems when running jest to unit test the components using this mixin throwing the error.

ReferenceError: $ is not defined

我知道我可以通过在browserify中包含jQuery来解决此问题,但这会将2个副本加载到我的网站中.

I know I can fix this by including jQuery through browserify, but that will load 2 copies into my site.

有什么玩笑的办法告诉我的react组件jQuery已经存在于窗口中并且不用担心吗?

Is there any way in jest to tell my react component that jQuery already exists on the window and not to worry about it?

推荐答案

我有一个类似的问题,但我认为到目前为止我可以解决您的问题. 您需要在React文件中使用require来在$

I have a similar problem but I think where i've got to so far solves your problem. You need to use require inside your react files to define jQuery under $

var $ = require('jquery');

MyMixin = {
   trackStructEvent: function () {
      args = Array.prototype.slice.call(arguments);
      $('body').trigger('myEvent', args);
   }
module.exports = MyMixin

然后您需要告诉玩笑不要模拟jquery

You then need to tell jest not to mock jquery

jest.dontMock('jquery')

然后您的笑话单元测试应该通过(假设它们没有验证jQuery正在执行的操作-这是我的测试失败的地方).

Then your jest unit tests should pass (assuming they aren't verifying things that jQuery is doing - this is where my tests are falling over).

您还需要告诉browserify jQuery是外部的,结果将是您对$的所有引用均已定义,jquery库已加载以进行测试,但未包含在browserify捆绑包中. (使用 browserify-shim )

You also need to tell browserify that jQuery is external then the result will be that all your references to $ have been defined, the jquery library is loaded for testing but is not included in your browserify bundle. (use browserify-shim)

这篇关于使用jQuery进行组件响应而不需要-开玩笑的单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆