[Angular & Unit Testing] Automatic change detection
2023-09-14 09:00:51 时间
When you testing Component rendering, you often needs to call:
fixture.detectChanges();
For example:
it('should display original title', () => { fixture.detectChanges(); expect(el.textContent).toContain(comp.title); }); it('should display a different test title', () => { comp.title = 'Test Title'; fixture.detectChanges(); // After change the prop of comp instance, call detectChanges() expect(el.textContent).toContain('Test Title'); });
You can also set auto change detection:
import { ComponentFixtureAutoDetect } from '@angular/core/testing';
Add to providers:
TestBed.configureTestingModule({ declarations: [ BannerComponent ], providers: [ { provide: ComponentFixtureAutoDetect, useValue: true } ] })
Tests wit auto change detection:
it('should display original title', () => { // Hooray! No `fixture.detectChanges()` needed expect(el.textContent).toContain(comp.title); }); it('should still see original title after comp.title change', () => { const oldTitle = comp.title; comp.title = 'Test Title'; // Displayed title is old because Angular didn't hear the change :( expect(el.textContent).toContain(oldTitle); }); it('should display updated title after detectChanges', () => { comp.title = 'Test Title'; fixture.detectChanges(); // detect changes explicitly expect(el.textContent).toContain(comp.title); });
相关文章
- [Angular] Using the platform agnostic Renderer & ElementRef
- [Angular 2] @Input & @Output Event with ref
- [AWS - DA] CLI & Policies
- [Angular 2] ElementRef, @ViewChild & Renderer
- [Angular 2] More on *ngFor, @ContentChildren & QueryList<>
- [Angular 2] ng-control & ng-control-group
- 华为OD机试 - 迷宫问题(Java & JS & Python)
- 大专&普通本科、搞算法的(蓝桥杯、ACM、天梯赛)-后续成长之路
- 区间DP与贪心算法的联系(uav Cutting Sticks && poj Fence Repair(堆的手工实现))
- 【大数据&AI人工智能】数字孪生:为城市和你创造一个虚拟副本
- HDU 2120 Ice_cream's world I(并检查集合)
- leetcode笔记:Pascal's Triangle
- 设计一个算法,求非空二叉树中指定的第k层(k>1)的叶子节点的个数
- UVA 12103 - Leonardo's Notebook(数论置换群)
- Android打包 & Gradle用法
- 腾讯笔试题——猴子吃桃(Python&C语言实现)
- nginx 惊群问题解决 && 条件变量虚假唤醒为什么不学着点?