我正在尝试对我的组件进行单元测试,但它立即生成一个错误:
类型错误:this.store$.pipe 不是函数
根据我的理解, createSpyObj 应该模拟状态。我有不同的选项选项,但没有一个起作用。
@Component({
selector: 'someSelector',
.....
})
export class SomeComponent implements OnInit, OnDestroy {
public isCon: boolean;
public dropdown: string[];
private isComponentActive: boolean = true;
constructor(@Inject(MAT_DIALOG_DATA) public data: any, private store$: Store<State>) {
this.isCon = data.isCon;
}
ngOnInit(): void {
this.store$.pipe(
select(this.returnColumns()),
takeWhile((): boolean => this.isComponentActive)
).subscribe((dropdown: []): void => this.setDropdown(dropdown));
}
private setDropdown(dropdown: []): void {
this.dropdown= filter(dropdown, (key): boolean => !key.isTrue)
.map((m): string => m.name);
}
private returnColumns() {
return this.isCon ? getConCol : getEmpCol;
}
ngOnDestroy(): void {
this.isComponentActive = false;
}
}
我的测试:
describe('SomeComponent', () => {
let component: SomeComponent;
let fixture: ComponentFixture<SomeComponent>;
const mockDialogData: object = {
isCon: true
};
const mockStoreData: ColumnDisplay[] = ['someData']
];
const testStore = jasmine.createSpyObj('Store', ['select']);
beforeEach(async () => {
TestBed.configureTestingModule({
declarations: [SomeComponent],
schemas: [NO_ERRORS_SCHEMA],
imports: [MatDialogModule],
providers: [
{ provide: MAT_DIALOG_DATA, useValue: mockDialogData },
{ provide: Store, useValue: testStore }
]
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(SomeComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', async () => {
testStore.select.and.returnValue(from([]));
expect(component).toBeTruthy();
});
it('should display correct selection rows when dialog opened', () => {
component.ngOnInit();
... more assertions goes here
});
});
期望从商店获取模拟数据以进行断言。
最佳答案
我通过以这种方式模拟商店来解决:
beforeEach(() => {
class StoreMock {
select = jasmine.createSpy().and.returnValue(of({}));
dispatch = jasmine.createSpy();
pipe = jasmine.createSpy().and.returnValue(of('success'));
}
TestBed.configureTestingModule({
providers: [
{
provide: Store,
useClass: StoreMock
},
provideMockStore()
]
});
TestBed.inject(Store);
const store$ = TestBed.inject(Store);
请注意,现在您可以模拟构造函数:const testComponent = new TestComponent(store$);
希望,这有帮助。
关于angular - 对话框测试 - 当我模拟 this.store$.pipe( select(...) ...).subscribe(..) 时,Jasmine 返回 this.store$.pipe 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57315652/