业力测试中未定义 jQuery 错误

ymr*_*mrs 3 jquery systemjs angular5

我在我的 angular 5 应用程序中使用 jQuery,它运行良好,但我在业力测试方面遇到了问题。

import { ElementRef } from '@angular/core';
declare var jQuery: any;

export class Item {

constructor(private element: ElementRef) {
    this.init();
}

private init() {
    this.$item = jQuery(this.element.nativeElement);
...
Run Code Online (Sandbox Code Playgroud)

错误

参考错误:未定义 jQuery。

包.json

"dependencies": {
  "jquery": "3.1.1"
}
Run Code Online (Sandbox Code Playgroud)

我已将 jquery 添加到我的 karma.conf 中,但这并没有帮助。

files: [
        'node_modules/core-js/client/shim.js',
        'node_modules/systemjs/dist/system.src.js',
        'node_modules/zone.js/dist/zone.js',
        'node_modules/zone.js/dist/proxy.js',
        'node_modules/zone.js/dist/sync-test.js',
        'node_modules/zone.js/dist/jasmine-patch.js',
        'node_modules/zone.js/dist/async-test.js',
        'node_modules/zone.js/dist/fake-async-test.js',
        'node_modules/tslib/tslib.js',
        'node_modules/jquery/dist/jquery.js',

        {pattern: 'node_modules/rxjs/**/*.js', included: false, watched: false },
        {pattern: 'node_modules/rxjs/**/*.js.map', included: false, watched: false },
        {pattern: '../karma-test-shim.js', included: true, watched: true},
        {pattern: 'node_modules/@angular/**/*.js', included: false, watched: false},
        {pattern: 'node_modules/@angular/**/*.js.map', included: false, watched: false},
        {pattern: 'node_modules/@ng-idle/core/bundles/core.umd.js', included: false, watched: false},
        {pattern: 'node_modules/bowser/bowser.js', included: false, watched: false},
        {pattern: 'node_modules/bootstrap/dist/js/bootstrap.js', included: false, watched: false},
        {pattern: 'node_modules/tslib/tslib.js', included: false, watched: false},
        {pattern: 'node_modules/jquery/dist/jquery.js', included: false, watched: false}
    ],
    proxies: {
        "/node_modules/": "../../node_modules/"
    },
    autoWatch: true,
    browsers: ['PhantomJS', 'Chrome', 'HeadlessChrome'],
    singleRun: false
});
};
Run Code Online (Sandbox Code Playgroud)

你有人可以帮忙吗?

提前致谢。

小智 6

从 Angular 6 / Karma 1.7.1 / Jasmine 2.99 + 开始,以上答案似乎已经过时 + 因为他们要求从 karma.conf.js 中删除文件和预处理器条目。

您需要将此(注意配置的scripts属性test)添加到angular.json文件中

"test": {
  "builder": "@angular-devkit/build-angular:karma",
  "options": {
    "main": "src/test.ts",
    "polyfills": "src/polyfills.ts",
    "tsConfig": "src/tsconfig.spec.json",
    "karmaConfig": "src/karma.conf.js",
    "styles": [],
    "scripts": [
      "node_modules/jquery/dist/jquery.min.js",
      "node_modules/datatables.net/js/jquery.dataTables.js"
    ]
  }
},
Run Code Online (Sandbox Code Playgroud)