使用 Angular 16 和 Jasmine/Karma。
我订阅了一个名为tableList$
ngOnInit() {
const { pageNumber } = this.subscribersService.getMiscValues();
this.subscribersService.initPage(pageNumber);
>> this.subscribersService.tableList$.subscribe((tableList) => {
// this.tableList = this.deleteSubscribersService.setDeleteCheckboxStates(tableList);
});
}
我正在尝试嘲笑行为主题,但我却得到了this.subscribersService.tableList$.subscribe is not a function
。
请问我做错了什么吗?
注意,我也尝试过,subscribersServiceMock.tableList$.and.returnValue({ subscribe: () => tableListMock$.subscribe });
但没有成功
fdescribe('ManageSubscribersComponent', () => {
let component: ManageSubscribersComponent;
let fixture: ComponentFixture<ManageSubscribersComponent>;
let miscMockValues;
let tableMockData;
let tableListMock$;
let dialogServiceMock
let dialogSubjectMock;
let subscribersServiceMock;
let deleteSubscribersServiceMock;
const displayedColumns = [
'id',
'name',
'description',
'createdBy',
'createdOn',
'updatedBy',
'updatedOn',
];
beforeEach(() => {
tableListMock$ = new Subject();
dialogSubjectMock = new Subject();
dialogServiceMock = jasmine.createSpyObj([
'open',
'afterClosed',
]);
deleteSubscribersServiceMock = jasmine.createSpyObj([
'deleteSubscribers',
]);
subscribersServiceMock = jasmine.createSpyObj([
'resetMiscValues',
'getMiscValues',
'initPage',
'tableList$',
]);
miscMockValues = {
pageNumber: 1,
pageSize: 25,
sort: '',
active: true,
testMode: false,
searchTerms: '',
};
subscribersServiceMock.getMiscValues.and.returnValue(miscMockValues);
subscribersServiceMock.tableList$.and.returnValue(tableListMock$);
dialogServiceMock.afterClosed.and.returnValue(dialogSubjectMock);
TestBed.configureTestingModule({
declarations: [ManageSubscribersComponent],
imports: [
HttpClientTestingModule,
MatFormFieldModule,
MatIconModule,
MatSliderModule,
MatTableModule,
MatFormFieldModule,
MatInputModule,
BrowserAnimationsModule,
MatPaginatorModule,
MatDialogModule,
],
schemas: [
CUSTOM_ELEMENTS_SCHEMA,
NO_ERRORS_SCHEMA,
],
providers: [
{
provide: SubscribersService,
useValue: subscribersServiceMock,
},
{
provide: DeleteSubscribersService,
useValue: deleteSubscribersServiceMock,
},
],
});
fixture = TestBed.createComponent(ManageSubscribersComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
fit('should init', fakeAsync(() => {
fixture.whenStable().then(() => {
expect(component.displayedColumns).toEqual(displayedColumns);
expect(subscribersServiceMock.getMiscValues).toHaveBeenCalled();
})
}));
正如评论中所述,问题在于测试设置
SubscribersService
通过以下方式设置模拟数组中的这些名称将是根据文档创建间谍的方法
createSpyObj
但是,
SubscribersService
用作tableList$
属性。因为它this.tableList$
是某种可观察的对象,所以不会像调用方法那样调用它:this.tableList$()
。如果您想要
tableListMock
为该tableList$
属性创建一个具有主题的对象,则可以使用下一个可选参数createSpyObj
:正如
createSpyObj
文档所述,最后一个参数可以定义要为其创建间谍的属性。或者一个对象,用于实际定义对象中的属性及其值。您还可以传递方法名称数组:
然后,将为属性访问器创建间谍。这样,您就可以监视何时
tableList$
是get
或set
。以下是如何配置
get
间谍以便subscribersServiceMock.tableList$
返回模拟主题:如果你只想设置值,那么有点麻烦,以前传递对象的方法更短。虽然这样你可以
tableList$
使用间谍来验证是否被访问: