首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用jQuery和jQuery UI运行任何Jest测试时出现的问题

使用jQuery和jQuery UI运行任何Jest测试时出现的问题
EN

Stack Overflow用户
提问于 2019-03-13 02:16:54
回答 2查看 2.3K关注 0票数 2

因此,我有一个名为Angular-Slickgrid的开源库,它还没有测试,我正在尝试使用它,但它真的很难使用。该库是旧的jQuery datagrid库(SlickGrid)的包装器,该库也使用jQuery UI。我想我已经部分解决了jQuery的问题(甚至不确定),但是jQuery UI仍然抱怨。还要注意的是,我对Angular中的Jest和单元测试还很陌生,但我真的希望它能正常工作,让我的库更安全。

您可以在GitHub上看到我为尝试使用我的开源库实现Jest所做的所有代码更改的提交。提交是here。如果这样做更容易的话,你可以随意创建一个公关。我使用以前版本的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服务和组件创建,这将是一个很好的开始,但我不能通过jQuery和jQuery UI问题,即使我不想测试任何核心库(SlickGrid),也不想测试jQuery和jQuery UI。

编辑

感谢在jQueryjQuery-UI上@brian-lives- got给出的答案,让我走得更远。现在我有另一个直接在Constructor中使用的@Inject()的小问题(也就是将配置传递给我的组件库),我不确定如何解决这个问题,如果有人知道如何解决,请帮助。

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(),我可以在beforeEach中使用overrideComponent()来修复,如下所示

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

最后,我现在可以说我运行了Jest!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-03-19 19:42:19

问题是jQuery是这样导入的:

import jQuery from 'jquery';

...which不能正常工作,并导致jQueryundefined

因为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的顶部...change到这个位置:

// 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';
// ...

...and将您的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错误的...and。

票数 4
EN

Stack Overflow用户

发布于 2021-04-27 21:04:23

在您的jest.config.js中添加以下行:

setupFiles: ['<rootDir>/src/test-env.js']

将您的test-env.ts更改为:

import * as jQuery from 'jquery';
window.$ = window.jQuery = jQuery;
global.$ = global.jQuery = jQuery;

import 'jquery-ui/ui/version';
import 'jquery-ui/ui/plugin';
import 'jquery-ui/ui/widget';
import 'jquery-ui/ui/widgets/mouse';
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55128237

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档