【发布时间】:2022-02-12 18:39:25
【问题描述】:
我想知道如何测试 .subscribe 回调中的代码,订阅位于 NgRx 存储选择器上。
环境:Angular 13、RxJs 7+、NgRx 13、Jest 27
考虑
my-component.ts
...
ngOnInit {
this.myValue = true;
this.store.select(mySelector).pipe(filter(data => data.attribute === true)).subscribe(data => {
this.myValue = false; // I want to test this
}
}
...
my-component.spec.ts
describe('MyComponent', () => {
let component: MyComponent;
let fixture: ComponentFixture<MyComponent>;
let store: MockStore;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [MyComponent],
imports: [...],
providers: [
provideMockStore({
initialState: { myFeature: { } },
}),
],
}).compileComponents();
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
fixture.detectChanges();
store = TestBed.inject(MockStore);
});
it('should perform animation & redirect to /dashboard if login successful', () => {
store.setState({
myFeature: {
...
attribute: true,
},
});
expect(component.myValue).toBe(false);
});
这可行,但它是随机的。由于这是异步的,我可以在调用 subscribe 回调之前测试 myValue 并且测试会失败,例如,如果我的 subscribe 回调需要时间来做一些事情,就像这样(我添加了 500 毫秒的延迟):
...
ngOnInit {
this.myValue = true;
this.store.select(mySelector).pipe(filter(data => data.attribute === true), delay(500)).subscribe(data => {
this.myValue = false; // I want to test this
}
}
...
这失败了。
在测试我的值之前如何等待回调执行?我可以在测试之前等待任意时间(例如 1 秒),但它可能会在未来的任何时候中断,它不够强大。喜欢:
it('should perform animation & redirect to /dashboard if login successful',
async () => {
store.setState({
myFeature: {
...
attribute: true,
},
});
await lastValueFrom(timer(600)); //rxjs 7
expect(component.myValue).toBe(false);
});
感谢您的帮助
【问题讨论】: