gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 07:41:00 27 4
gpt4 key购买 nike

我有一个使用 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com