Angular6 和 JQuery - 布局不是 Karma 的功能



我正在使用一些JQuery来解决我正在使用的库上的视觉错误。 它运行良好,但是现在我正在努力开发经过测试的版本,我遇到了一个错误。

所以,在我的组件中,我有:

declare var $: any;
@Component({ // })
export class MainComponent {
constructor() {
$('body').layout('fix')
}
}

karma.conf.js中,我有以下一行:

files: [
'../node_modules/jquery/dist/jquery.min.js',   
],

当我启动一个ng test时,会出现此错误:

TypeError: $(...).layout is not a function

任何建议将不胜感激。

将其包裹在文档周围准备好了。

constructor() {
$(document).ready(function() {
$('body').layout('fix')
});
}   

但我强烈建议尽可能少地使用 jquery 和 angular

在文件的scripts部分中链接angular.jsonJQuery 文件。

这是angular.json的结构 - https://github.com/angular/angular/blob/master/aio/angular.json

我还建议用ngOnInit()方法而不是constructor()编写代码。

步骤:

1(在index.html将下面的行放在标签中。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

2(在下面的组件ts文件中,您必须像这样声明var

import { Component } from '@angular/core';
declare var jquery:any;
declare var $ :any;
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
ngOnInit(){
$('body').layout('fix'); //
}
}

现在您可以根据需要使用它。 如果它不适用于karma请尝试以这种方式定义它:

files: [
{ pattern: './node_modules/jquery/dist/jquery.min.js', watched: false },    
]

制作watched option false

最新更新