使用jQuery和jQuery UI运行任何Jest测试的问题

问题描述 投票:2回答:1

所以我有一个名为Angular-Slickgrid的开源库,它还没有测试,我正在尝试使用Jest,但它真的很难用它。该库是旧的jQuery数据网格库(SlickGrid)的包装,它也使用jQuery UI。我认为我部分地解决了jQuery问题(甚至不确定),但jQuery UI仍然抱怨。另请注意,我是Angular中的Jest和Unit Testing的新手,但我真的希望这可以工作并使我的lib更安全。

您可以在GitHub上看到我尝试使用我的开源库实现Jest所做的所有代码更改。提交是here。如果这更容易,请随意创建PR。我使用之前版本的Jest(23.6.0)而不是最新版本,因为我有最新的其他问题。

这是我目前的错误

FAIL  src/app/modules/angular-slickgrid/components/angular-slickgrid.component.spec.ts
Test suite failed to run 
TypeError: Cannot read property 'ui' of undefined
  at node_modules/jquery-ui-dist/jquery-ui.js:18:10
  at Object.<anonymous>.$.ui (node_modules/jquery-ui-dist/jquery-ui.js:14:3)
  at Object.<anonymous> (node_modules/jquery-ui-dist/jquery-ui.js:16:2)
  at Object.<anonymous> (src/app/modules/angular-slickgrid/components/angular-slickgrid.component.ts:11193:1)
  at Object.<anonymous> (src/app/modules/angular-slickgrid/components/angular-slickgrid.component.spec.ts:7:37)

我试图使用unmock('jquery')unmock('jquery-ui'),但这似乎没有帮助。这是失败的测试

jest.unmock('jquery');
jest.unmock('jquery-ui');
import { TestBed, async } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';

import { AngularSlickgridComponent } from './angular-slickgrid.component';

describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        AngularSlickgridComponent
      ],
      providers: [],
      imports: [RouterTestingModule]
    }).compileComponents();
  }));

  it('should create the app', async(() => {
    const fixture = TestBed.createComponent(AngularSlickgridComponent);
    const app = fixture.debugElement.componentInstance;
    expect(app).toBeTruthy();
  }));
});

还有我的jest.config.js

module.exports = {
  globals: {
    'ts-jest': {
      tsConfigFile: './src/tsconfig.spec.json',
    },
    __TRANSFORM_HTML__: true,
  },
  testMatch: ['**/__tests__/**/*.+(ts|js)', '**/+(*.)+(spec|test).+(ts|js)'],
  setupFiles: ['<rootDir>/test-env.ts'],
  setupTestFrameworkScriptFile: '<rootDir>/node_modules/@angular-builders/jest/src/jest-config/setup.js',
  transform: {
    '^.+\\.(ts|html)$': '<rootDir>/node_modules/jest-preset-angular/preprocessor.js',
  },
  transformIgnorePatterns: ['node_modules/(?!@ngrx)'],
  moduleDirectories: [
    "node_modules",
    "src/app",
  ],
  collectCoverage: true,
  moduleFileExtensions: [
    'ts',
    'json',
    'js'
  ],
  testResultsProcessor: 'jest-sonar-reporter',
  moduleNameMapper: {
    "app/(.*)": "<rootDir>/src/app/$1",
    "@common/(.*)": "<rootDir>/src/app/common/$1",
  }
};

最后是一个测试设置,为Jest全局导入jQuery

import jQuery from 'jquery';
declare var window: any;
declare var global: any;
window.$ = window.jQuery = jQuery;
global.$ = global.jQuery = jQuery;

我希望完成的是至少测试我的Angular Services和Component创建,这将是一个良好的开端,但我无法通过jQuery和jQuery UI问题,即使我不想测试任何核心库(SlickGrid),既不是jQuery,也不是jQuery UI。

编辑

感谢@ brian-lives-outdoors获得jQueryjQuery-UI的答案,我得到了更多。现在我有另一个小问题,@Inject()直接使用Constructor(即将配置传递给我的组件库),我不知道如何解决它,如果有人知道请帮忙。

constructor(
  private elm: ElementRef,
  // ... more Services import
  //
  @Inject('config') private forRootConfig: GridOption
) {}

而错误是

StaticInjectorError(DynamicTestModule)[config]:
  StaticInjectorError(Platform: core)[config]:
    NullInjectorError: No provider for config!

at NullInjector.get (../packages/core/src/di/injector.ts:43:13)
at resolveToken (../packages/core/src/di/injector.ts:346:20)
...

最后编辑问题的答案

我找到了如何修复Constructor@Inject(),我可以用overrideComponent()里面的beforeEach那样做,如下图所示

beforeEach(async(() => {
  TestBed.configureTestingModule({
    declarations: [
      AngularSlickgridComponent,
      SlickPaginationComponent
    ],
    providers: [
      // ... all Services
    ],
    imports: [
      RouterTestingModule,
      TranslateModule.forRoot()
    ]
  })
  // THIS LINE is for the @Inject('config')
  .overrideComponent(AngularSlickgridComponent, {
    set: { providers: [{ provide: 'config', useValue: {} }] },
  })
  .compileComponents();
}));

最后我现在可以说我开玩笑了!

jquery angular jestjs slickgrid angular-test
1个回答
3
投票

问题是jQuery是这样导入的:

import jQuery from 'jquery';

...这是行不通的,导致jQuery成为undefined

因为jQuery作为undefined导入,全局$被设置为undefined,当jQuery UI尝试加载它时会抛出错误。


这个问题很奇怪,因为导入jQuery的语法显示了很多,即使是官方TypeScript文档中的import语法示例。


无论如何,您可以使用以下语法导入jQuery来解决问题:

import * as jQuery from 'jquery';


将你的test-env.ts改为:

import * as jQuery from 'jquery';
declare var window: any;
declare var global: any;
window.$ = window.jQuery = jQuery;
global.$ = global.jQuery = jQuery;

...将angular-slickgrid.components.ts的顶部更改为:

// import 3rd party vendor libs
// only import the necessary core lib, each will be imported on demand when enabled (via require)
import 'jquery-ui-dist/jquery-ui';
import 'slickgrid/lib/jquery.event.drag-2.3.0';
import 'slickgrid/slick.core';
import 'slickgrid/slick.grid';
import 'slickgrid/slick.dataview';

// ...then everything else...
import { AfterViewInit, Component, ElementRef, EventEmitter, Inject, Injectable, Input, Output, OnDestroy, OnInit } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { GlobalGridOptions } from './../global-grid-options';
// ...

...并将你的angular-slickgrid.component.spec.ts改为:

import { TestBed, async } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';

import { AngularSlickgridComponent } from './angular-slickgrid.component';

describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        AngularSlickgridComponent
      ],
      providers: [],
      imports: [RouterTestingModule]
    }).compileComponents();
  }));

  it('should create the app', async(() => {
    const fixture = TestBed.createComponent(AngularSlickgridComponent);
    const app = fixture.debugElement.componentInstance;
    expect(app).toBeTruthy();
  }));

  it(`should have as title 'Angular SlickGrid Demo'`, async(() => {
    const fixture = TestBed.createComponent(AngularSlickgridComponent);
    const app = fixture.debugElement.componentInstance;
    expect(app.title).toEqual('Angular SlickGrid Demo');
  }));
});

......这会让你超越你最初的jQuery错误。

© www.soinside.com 2019 - 2024. All rights reserved.