【问题标题】:Angular unit test error ($ is not defined)Angular 单元测试错误($ 未定义)
【发布时间】:2019-03-18 21:47:51
【问题描述】:

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

这里是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'导入{组件,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: (?, ?).

我尝试了许多不同的方法来让它工作,但没有一个工作。请帮忙!

【问题讨论】:

    标签: jquery angular datatables jasmine


    【解决方案1】:

    问题解决了!

    我需要将此(注意test 配置的scripts 属性)添加到我的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"
            ]
          }
        },
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-05
    • 2020-08-31
    • 2014-03-22
    • 1970-01-01
    • 2019-03-26
    • 2023-02-17
    • 1970-01-01
    相关资源
    最近更新 更多