gpt4 book ai didi

angular - 在 ngOnInit 中测试一个可观察的间隔

转载 作者:行者123 更新时间:2023-12-01 04:23:02 26 4
gpt4 key购买 nike

我一直试图让这个测试运行一天多,但我没有选择。

我尝试过使用 fakeAsync 的变体,并注入(inject) testScheduler ,但 tick()函数似乎没有效果,并且,正如我将描述的,注入(inject) testScheduler效果太好了。

我想测试的功能是这样的:

ngOnInit() {
...
interval(environment.verificationCheckPollingInterval).pipe(takeUntil(this.destroy)).subscribe(_ =>
this.store.dispatch(fromAccount.checkEmailVerificationStatus()));
}


我确实意识到对电子邮件验证进行轮询并不是理想的做法,但这是另一天的故事。

我的 Jasmine 测试功能如下所示:

describe('After the verification interval has elapsed', () => {
it('should dispatch a check verification email action after the verification interval has elapsed', fakeAsync(() => {
tick(environment. environment.verificationCheckPollingInterval);
fixture.detectChanges();
testScheduler.run(({ expectObservable, flush, cold }) => {
expectObservable(store.scannedActions$.pipe(
ofType(fromAccount.ActionTypes.checkEmailVerificationStatus),
map((_) => true))).toBe('a', { a: true });
});
}));
});
tick函数似乎什么都不做。

另一种方法是注入(inject) scheduler进入组件,并将订阅更改为

interval(environment.verificationCheckPollingInterval, this.scheduler).pipe(takeUntil(this.destroy)).subscribe(_ =>
this.store.dispatch(fromAccount.checkEmailVerificationStatus()));

然后在我的测试设置中,包括

{ provide: Scheduler, useValue: testScheduler }

但这太有效了(除了我将修改生产代码以支持测试,这远非理想)。它工作得很好的原因是,如果我在订阅处理程序上放置一个断点,它会被重复调用而没有任何延迟,并且在每一步, testScheduler.frame值已提前 1000帧(我的轮询间隔是 1 秒)。这会挂起我的浏览器,并使我的笔记本电脑发热得有些惊人。

我错过了什么吗?有没有办法测试 interval没有让我的笔记本电脑着火?

更新

我有一个非常明智的建议,不幸的是失败了。

鉴于此代码:

describe('After the verification interval has elapsed', () => {
it('should dispatch a check verification email action after the verification interval has elapsed', (done) => {
store.scannedActions$.pipe(
ofType(fromAccount.ActionTypes.checkEmailVerificationStatus),
take(1)).subscribe(x => {
console.log('action dispatched', x);
done();
});
});
});
console.log调用被调用,但测试失败并显示消息

Error: Timeout - Async callback was not invoked within 5000ms (set by jasmine.DEFAULT_TIMEOUT_INTERVAL)

最佳答案

您可以简单地订阅 store并调用done当你完成测试时。

更多信息,您可以阅读 here

describe('After the verification interval has elapsed', () => {
it('should dispatch a check verification email action after the verification interval has elapsed', (done) => {
store.scannedActions$.pipe(
ofType(fromAccount.ActionTypes.checkEmailVerificationStatus))
.subscribe(_ => {
// run your tests here
done();
});
});
});

关于angular - 在 ngOnInit 中测试一个可观察的间隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60467909/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com