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

时间:2019-03-18 21:47:51

标签: jquery angular datatables jasmine

尝试测试组件时,我总是收到错误消息。

这里是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();
  });
});

还有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() {}
}

运行此命令会给我错误:

Failed: $ is not defined

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

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

我尝试了多种方法来使它起作用,但是没有一个起作用。请帮忙!

1 个答案:

答案 0 :(得分:0)

问题已解决!

我需要将此文件(请注意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"
        ]
      }
    },