角度单元测试错误($未定义)

Jer*_*itz 6 jquery datatables jasmine angular

我在尝试测试我的组件时不断收到错误。

这是my.component.spec.ts

import { ComponentFixture, TestBed, async } from '@angular/core/testing';
import { MyComponent } from './my.component';
import { LocalStorageService } from '../../services/local-storage.service';
import { DataTablesModule } from 'angular-datatables';

fdescribe('MyComponent', () => {
  let component: MyComponent;
  let fixture: ComponentFixture<MyComponent>;
  let de: DebugElement;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [MyComponent],
      imports: [DataTablesModule.forRoot()],
      providers: []
    }).compileComponents().then(() => {
      fixture = TestBed.createComponent(MyComponent);
      component = fixture.componentInstance;
      fixture.detectChanges();
    });
  }));

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});
Run Code Online (Sandbox Code Playgroud)

my.component.ts

从 '@angular/core' 导入 { Component, OnInit };

@Component({
  selector: 'app-my',
  template: `
    <table datatable [dtOptions]="dtOptions">
      <thead>
        <tr>
          <th>Column A</th>
          <th>Column B</th>
        </tr>
      </thead>
      <tbody>
        <tr *ngFor="let col of myColumns">
          <td></td>
          <td></td>
        </tr>
      </tbody>
    </table>
  `,
  styleUrls: []
})
export class MyComponent implements OnInit {
  myColumns: any[] = [];

  constructor() { }

  ngOnInit() {}
}
Run Code Online (Sandbox Code Playgroud)

运行这个给我错误:

Failed: $ is not defined

当我尝试import * as $ from 'jquery'添加$到提供程序时,出现此错误:

Failed: Can't resolve all parameters for jQuery: (?, ?).

我尝试了很多不同的方法来让它发挥作用,但没有一个有效。请帮忙!

Jer*_*itz 6

问题解决了!

我需要将其添加到我的文件中(注意配置scripts的属性testangular.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)