jquery - Angular 5 : How to import jQuery in Jest test?

标签 jquery angular mocking angular5 jestjs

我有一个使用 CalendarService 的 Angular 组件。 当组件初始化时,我调用“calendarService.init()”方法。

这个CalendarService设置了semantic-ui-calendar的配置(基于jQuery),代码类似于“$(myElement).calendar(settings);”。

当我使用 Jest 测试我的组件时,组件的初始化出现错误:“ReferenceError: $未定义”。

我该如何修复它?

搜索.组件.spec.ts:

describe('SearchComponent', () => {

  let fixture: ComponentFixture<SearchComponent>;
  let component: SearchComponent;
  let element: DebugElement;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        AppModule
      ],
      providers: [
        { provide: APP_BASE_HREF, useValue : '/search' },
        CalendarService
      ]
    });

    fixture = TestBed.createComponent(SearchComponent);

    let calendarService = TestBed.get(CalendarService);

    component = fixture.componentInstance;
    element = fixture.debugElement;

    fixture.detectChanges();
  }));
});

搜索.component.ts:

@Component({
  selector: 'afo-search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.less']
})
export class SearchComponent implements OnInit, AfterViewInit {

  constructor(private calendarService: CalendarService) { }

  ngOnInit() {
  }

  ngAfterViewInit() {
    this.calendarService.init();
  }

}

日历.service.ts:

@Injectable()
export class CalendarService {

  constructor() {
  }

  init() {
    $('.ui.calendar.field').calendar();
  }
}

最佳答案

我找到了解决方案:

我需要在 setupJest.ts 中添加以下行:

import * as $ from 'jquery';
Object.defineProperty(window, '$', {value: $});
Object.defineProperty(global, '$', {value: $});
Object.defineProperty(global, 'jQuery', {value: $});

一开始,我尝试了这个解决方案:

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

但是 global.xxx 和 window.xxx 未知。

参见:

https://github.com/thymikee/jest-preset-angular#allow-vendor-libraries-like-jquery-etc

https://github.com/facebook/jest/issues/708

关于jquery - Angular 5 : How to import jQuery in Jest test?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48791237/

相关文章:

javascript - Angular5无法读取未定义的属性 'length'

c# - 模拟对象的属性以返回来自对象本身的值

javascript - 如何使用 Jest 模拟和测试包装模块函数的方法?

asp.net-mvc - 如何在MVC单元测试类中模拟Request.Files[]?

javascript - 来自同一页面的多个 websocket,使用 java 作为服务器端

javascript - $f 在 jquery 脚本中是什么意思?

angular - 在第一个值发射后,主体从数组中失去观察者。 Angular RouteReuseStrategy 表编辑表单通信

javascript - Angular 2 中流的更改检测?

jquery - 用你自己的 css 覆盖 css

javascript - 如何使用 jQuery 将元素动画化为其自然高度