Angular 5:如何在Jest测试中导入jQuery?

时间:2018-02-14 15:54:29

标签: jquery angular mocking angular5 jest

我有一个使用CalendarService的角度组件。 当组件是init时,我调用“calendarService.init()”方法。

这个CalendarService设置了一个语义ui-calendar(基于jQuery)的配置,代码如“$(myElement).calendar(settings);”。

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

我该如何解决?

search.component.spec.ts:

example.com.key

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

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

}

2 个答案:

答案 0 :(得分:0)

你导入了jquery吗?

declare var jquery:any;   // not required
declare var $ :any;   // not required

答案 1 :(得分:0)

我找到了解决方案:

我需要在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