我有这个测试。
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 函数添加到这个安装程序开玩笑文件中,以使其获取验证函数?还是有其他解决方案?
不能评论 Jest 的东西,但$('.foo').validate()
不是原生的 jQuery 方法。它需要jQuery验证插件(或者可能是其他具有validate()
方法的插件,但这是我最常看到的插件(。
您是否在项目中安装了jquery-validation
?
要使用jQuery验证,请将其导入测试中
import validate from 'jquery-validation';
test('validation', function () {
expect(validate).toBeDefined();
});
你还需要在你的设置中加入jQuery.js
import $ from 'jquery';
global.$ = global.jQuery = $;