在运行测试时无法找到JQuery'命令

时间:2017-10-12 05:08:59

标签: jquery angularjs typescript karma-jasmine angular-cli

我使用新的angular-cli版本创建了一个项目,我使项目启动并运行。当我运行服务和ng构建命令时,它可以完美地工作而不会出现任何错误。但是当我尝试运行ng测试时,它会向我显示这样的错误。

theme.provider.ts (53,31): Property 'removeClass' does not exist on type 'JQuery'.
theme.provider.ts (64,35): Property 'addClass' does not exist on type 'JQuery'.
theme.provider.spec.ts (7,30): Cannot find name '$'.

我已经通过以下方式将JQuery添加到angular-cli.json

"scripts": [
    "../node_modules/jquery/dist/jquery.min.js"
 ],

然后我通过这种方式将JQuery导入我的主模块

import 'jquery';

以上配置中是否有任何缺失的步骤?

1 个答案:

答案 0 :(得分:2)

假设您已安装@types/jquery,请尝试将jquery添加到tsconfig.spec.json中的类型列表中(列表中已有jasminenode )。

此外,当您将jquery.min.js添加到scripts中的angular-cli.json列表时,它会在您的scripts.bundle.js中结束。当您在主模块中执行import 'jquery';时,会在vendor.bundle.js中结束,因此您已添加了两次代码。

而不是import 'jquery';,只需将jquery添加到compilerOptions中的tsconfig.app.json类型列表中(或创建一个"types": ["jquery"])。然后,您将能够引用全局jquery对象而无需再次导入它。