Angular 测试设定间隔
我在测试使用setInterval的代码时遇到问题 我的功能是检查当前时间是否在给定时间之后 我所期望的是isAfter标志在开始时应为false,在6秒后在2,3,4秒时应为true应为false 现在它仍然是假的 组件代码Angular 测试设定间隔,angular,jasmine,karma-runner,setinterval,Angular,Jasmine,Karma Runner,Setinterval,我在测试使用setInterval的代码时遇到问题 我的功能是检查当前时间是否在给定时间之后 我所期望的是isAfter标志在开始时应为false,在6秒后在2,3,4秒时应为true应为false 现在它仍然是假的 组件代码 isAfter: boolean; private interval; ngOnInit(): void { const now = new Date(); const time = now.setSeconds(now.getSecond
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();
}));
});
此行通过引用进行比较,这里有两个不同的日期对象。您应该将其更改为:
if (now.getTime() === time.getTime())
而是比较两个原始数字。是的,坦克!我现在看到代码中有一个bug。现在应该>=时间EHHH此测试在Angular 2中不工作现在日期没有更新私有checkTimetime:any:void{this.interval=setInterval=>{const now=new date;console.lognow如果现在>=时间{console.log'stop';this.isAfter=true;clearIntervalthis.interval;}else{console.log'next';this.isAfter=false;}},1000;}我认为你不能像这样比较日期对象。同样,它应该是now.getTime>=time.getTime.Btw,对于任何日期时间操作,如果你在项目中的多个地方执行它们,那么添加库是值得的。是的,我有moment.js,问题是Angular 2中setInterval中的新日期或时刻没有更新。可能是我的package.json。我稍后再放。
if (now.getTime() === time.getTime())