首页 > 解决方案 > 如何模拟延迟?

问题描述

有包含状态的服务:

@Injectable({
  providedIn: 'root'
})
export class WordsService {

  words: string[] = [
    'qqq',
    'www',
    'eee',
    'rrr',
    'ttt',
    'yyy',
  ];

  constructor() { }

}

组件中有一个按钮。当用户单击此按钮时,服务状态将显示在模板中。

@Component({
  selector: 'app-page3',
  template: `
    <div *ngFor="let word of serviceWords" class="word-el">
        {{ word }}
    </div>
    <button (click)="getWordsFromService()" id="getWordsBtn">get words from service</button>
  `,
  styleUrls: ['./page3.component.scss']
})
export class Page3Component {
  serviceWords: string[] = [];
  constructor(private wordsService: WordsService) { }
  getWordsFromService() {
    this.serviceWords = this.wordsService.words;
  }
}

我尝试模拟延迟,然后检查在模板中显示服务状态。

beforeEach(async () => {
  await TestBed.configureTestingModule({
    declarations: [ Page3Component ]
  })
  .compileComponents();
});

it('should display list after getWords-button', () => {
  fixture.detectChanges();
  const compliedComponent = fixture.debugElement.nativeElement;

  const btn = compliedComponent.querySelector('#getWordsBtn');
  btn.dispatchEvent(new Event('click'));

  setTimeout(() => {
    expect(compliedComponent.querySelector('.word-el')).toBeTruthy();  
  }, 1000);
});

不幸的是,这个单元测试不起作用。我收到以下消息:规范没有期望

请帮我模拟按钮单击后的延迟。

我尝试使用tick()waits()但他们没有工作。

标签: angularunit-testingjasmine

解决方案


  1. 在这种情况下,您应该done在测试中使用 -arg,例如:
it('should display list after getWords-button', (done: DoneFn) => {
  fixture.detectChanges();
  const compliedComponent = fixture.debugElement.nativeElement;

  const btn = compliedComponent.querySelector('#getWordsBtn');
  btn.dispatchEvent(new Event('click'));

  setTimeout(() => {
    expect(compliedComponent.querySelector('.word-el')).toBeTruthy();
    done();
  }, 1000);
});
  1. 我认为更改检查的正确方法是检测夹具更改:
it('should display list after getWords-button', () => {
  fixture.detectChanges();
  const compliedComponent = fixture.debugElement.nativeElement;

  const btn = compliedComponent.querySelector('#getWordsBtn');
  btn.dispatchEvent(new Event('click'));
  fixture.detectChanges();

  expect(compliedComponent.querySelector('.word-el')).toBeTruthy();  
});

推荐阅读