j.2*_*2bb 4 jquery mocking jestjs angular angular5
我有一个使用 CalendarService 的角度组件。当组件初始化时,我调用“calendarService.init()”方法。
这个 CalendarService 设置了一个语义 UI 日历的配置(基于 jQuery),代码类似于“$(myElement).calendar(settings);”。
当我用 Jest 测试我的组件时,组件的初始化有一个错误:“ReferenceError: $ is not defined”。
我该如何解决?
search.component.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();
}));
});
Run Code Online (Sandbox Code Playgroud)
search.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();
}
}
Run Code Online (Sandbox Code Playgroud)
日历.service.ts:
@Injectable()
export class CalendarService {
constructor() {
}
init() {
$('.ui.calendar.field').calendar();
}
}
Run Code Online (Sandbox Code Playgroud)
我找到了解决方案:
我需要在我的 setupJest.ts 中添加以下几行:
import * as $ from 'jquery';
Object.defineProperty(window, '$', {value: $});
Object.defineProperty(global, '$', {value: $});
Object.defineProperty(global, 'jQuery', {value: $});
Run Code Online (Sandbox Code Playgroud)
一开始,我尝试了这个解决方案:
import $ from 'jquery';
window.$ = $;
global.$ = global.jQuery = $;
Run Code Online (Sandbox Code Playgroud)
但是 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了吗?
declare var jquery:any; // not required
declare var $ :any; // not required
Run Code Online (Sandbox Code Playgroud)