【发布时间】:2019-06-05 17:05:31
【问题描述】:
这看起来很简单,我知道我一定做错了什么,但我已经做了一整天,仍然无法通过一个简单的测试。我的组件使用第三方库 JQWidgets,部分问题是测试报告了该库中的错误,但测试失败的另一部分显然是我的模拟数据应该加载到组件中的属性中没有进入那里。
我正在尝试使用 Jest 模拟,但即使我现在已经阅读了十几次文档,我仍然不确定我是否做得对。有时我需要一个间谍,有时我只希望模拟函数(通常是服务函数)返回一些虚拟数据。我觉得我可能只是不了解 Jest 的一些嘲弄魔法。
对于任何含糊之处,我深表歉意,我希望有人在我的工作中可以问,但没有,所以我很谦虚地寻求帮助。
编辑:模拟整个服务这似乎工作得更好,因为我的测试断言通过了,但由于第三方模块中的错误,测试仍然失败。我试过添加 NO_ERRORS_SCHEMA 但没有帮助:
TypeError: bA.getPropertyValue is not a function
at R (node_modules/jqwidgets-scripts/jqwidgets/jqxcore.js:14:36743)
组件的 ngOnInit()
ngOnInit() {
this._dataService.getData().subscribe(
data => {
this.populate(data); // <--this line appears not to be running, as this function populates this.source.localdata with this data
this.dataAdapter = new jqx.dataAdapter(this.source);
},
error => {
console.error(error);
}
);
}
我的测试
import { ComponentFixture, TestBed, async } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { jqxGridComponent } from 'jqwidgets-scripts/jqwidgets-ts/angular_jqxgrid';
import { ProgressComponent } from './progress.component';
import { ProgressGridDataService } from './progress.service';
import { WorkingFileService } from 'src/app/services/working-file/working-file.service';
import { IProgressData } from './progress.interfaces';
import { of } from 'rxjs';
describe('ProgressComponent', () => {
let component: ProgressComponent;
let fixture: ComponentFixture<ProgressComponent>;
class ProgressServiceSpy {
testHistory: IProgressData = {
recordId: 1,
product: 'A',
};
getData = jest.fn().mockImplementation(() => of(Object.assign({}, this.testHistory)));
restartLoad = jest.fn();
}
beforeEach(
async(() => {
TestBed.configureTestingModule({
declarations: [ProgressComponent, jqxGridComponent],
providers: [
WorkingFileService,
{ provide: ProgressGridDataService, useValue: {} },
],
})
.overrideComponent(ProgressComponent, {
set: {
providers: [
{ provide: ProgressGridDataService, useClass: ProgressServiceSpy },
],
},
})
.compileComponents();
fixture = TestBed.createComponent(ProgressComponent);
component = fixture.componentInstance;
fixture.detectChanges();
})
);
describe('retry button', () => {
it('should call the restartLoad service and pass a record ID', () => {
component.ngOnInit();
expect(component.source).toHaveProperty('localdata');
expect(component.source.localdata).toEqual(testHistory);
});
});
});
【问题讨论】:
-
请给minimal reproducible example。一方面,您似乎怀疑您使用的是真正的合作者,并且在测试 组件而不是服务时显然需要使用
HttpClientTestingModule。 -
@jonrsharpe 即使这也让我有点过头了。以前我试图按照一些 Angular 文档示例来测试服务,而这只是留在那里。我切换到 HttpClientModule
标签: angular unit-testing mocking jestjs jqwidget