【发布时间】:2018-11-10 21:00:04
【问题描述】:
我正在使用 Jasmine 对 Angular 5 应用程序进行单元测试。我到了需要测试一个依赖于DomSanitizer的函数的地步:
loadImage() {
this.image = this.sanitizer.bypassSecurityTrustStyle(`url(${this.assetUrl})`);
}
我验证了这个函数可以完美运行,这意味着DomSanitizer 已经在构造函数中并且它的语法是正确的。
我的单元测试如下:
it('loads the Image', () => {
component.loadImage()
fixture.detectChanges();
expect(component.imageUrl).toBe('...');
});
此外,DomSanitizer 是 TestBed providers 的一部分:
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule,
CommonModule
],
declarations: [
MyComponent
],
providers: [
DomSanitizer
],
schemas: [ NO_ERRORS_SCHEMA ]
})
.compileComponents();
}));
然而,Jasmine 在对函数进行单元测试时抛出了这个错误:
ERROR: 'Unhandled Promise rejection:', '_this.sanitizer.bypassSecurityTrustStyle is not a function', '; Zone:', 'angular', '; Task:', 'Promise.then', '; Value:', TypeError: _this.sanitizer.bypassSecurityTrustStyle is not a function
有什么想法吗?
谢谢!
【问题讨论】:
-
从提供者中删除
DomSanitizer,而不是CommonModule,尝试使用BrowserModule -
你需要导入
BrowserModulestackoverflow.com/questions/39438039/… -
优秀。非常感谢!
标签: angular jasmine testbed angular-dom-sanitizer