【问题标题】:Vue, Jest, jQuery - Testing jQuery ValidationVue, Jest, jQuery - 测试 jQuery 验证
【发布时间】:2020-05-26 06:42:44
【问题描述】:

我有这个测试。

    test('Can registerFormListener', () => {
        const spy = jest.spyOn(wrapper.vm, "registerFormListener");
        wrapper.vm.registerFormListener();
        expect(spy).toBeCalled();
    });

这是在监视这个功能。

registerFormListener: function () {
oiService.initFormValidation(selection);
}

调用此验证函数。

static initFormValidation(selection: string, () => void) {
            $(selector).validate({
                rules: {
                    email: {
                        required: false,
                        email: true
                    },
                },
                messages: {
                    email: {
                        required: "Please enter an email"
                    },
                },
                submitHandler: function() {
                    onSubmit != null ? onSubmit() : null;
                }
            });
}

然而,Jest 并没有在这个函数中使用任何 jQuery。我收到错误TypeError: $(...).validate is not a function

我在 package.json 中安装了 jQuery,但要让 Jest 获取它,我必须添加一个 setup-jest.js 文件并告诉它获取我们使用的所有全局变量。

我是否还必须将这个和所有其他 jQuery 函数添加到这个 setup-jest 文件中,以获取验证函数?还是有其他解决方案?

【问题讨论】:

    标签: javascript jquery vue.js jestjs


    【解决方案1】:

    无法评论 Jest 的内容,但 $('.foo').validate() 不是原生 jQuery 方法。它需要jQuery validation plugin(或者可能是其他带有validate() 方法的插件,但这是我最常看到的)。

    您是否在项目中安装了jquery-validation

    【讨论】:

    • 感谢推荐!我对 jQuery 很陌生。我已经安装了jquery-validation,但 Jest 仍然在检测验证时遇到问题。
    【解决方案2】:

    要使用 jQuery 验证,您可以在测试中导入它

    import validate from 'jquery-validation';
    
    test('validation', function () {
        expect(validate).toBeDefined();
    });
    

    您还需要在 setup-jest.js 中使用 jQuery

    import $ from 'jquery';
    global.$ = global.jQuery = $;
    

    【讨论】:

      猜你喜欢
      • 2020-11-25
      • 1970-01-01
      • 2018-05-08
      • 2020-08-04
      • 2019-10-03
      • 2021-06-17
      • 1970-01-01
      • 2018-07-02
      • 2020-02-20
      相关资源
      最近更新 更多