我在使用setInterval的测试代码方面遇到问题。
我在组件中检查当前时间是否在给定时间之后的功能。
我期望的是isAfter标志在开始时应该为false,在6秒之后应该为true(在2,3,4秒处应该为false)
现在它仍然是错误的。
组件代码
isAfter: boolean;
private interval;
ngOnInit(): void {
const now = new Date();
const time = now.setSeconds(now.getSeconds() + 5);
const future = new Date(time);
this.checkTime(future);
}
private checkTime(time: any): void {
this.interval = setInterval(() => {
const now = new Date();
if (now === time) {
console.log('stop');
this.isAfter = true;
clearInterval(this.interval);
} else {
console.log('next');
this.isAfter = false;
}
}, 1000);
}
}
规范代码
import { TestBed, async, ComponentFixture, fakeAsync, tick, discardPeriodicTasks } from '@angular/core/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
let component: AppComponent;
let fixture: ComponentFixture<AppComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent
],
}).compileComponents();
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
}));
it ('should check time', fakeAsync(() => {
fixture.detectChanges();
console.log('isAfter 1', component.isAfter);
tick(3000);
fixture.detectChanges();
console.log('isAfter 3', component.isAfter);
tick(6000);
fixture.detectChanges();
console.log('isAfter 6', component.isAfter);
discardPeriodicTasks();
}));
});
答案 0 :(得分:1)
if (now === time)
此行通过引用进行比较,您在此处有两个不同的日期对象。您应该将其更改为:
if (now.getTime() === time.getTime())
而是比较两个原始数字。