angular - 在Angular中使用*ngIf隐藏时获取项目以进行测试
问题描述
我的 HTML:
<div *ngIf="state">
<p>some text<p>
<button (click)="increment()" class="myButton">Increment</button>
</div>
有我的组件
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
})
export class AppComponent {
state = false;
counter = 0;
constructor(private app: AppService, private http: HttpClient, private
router: Router
) {}
increment() {
this.counter += 1;
}
在我的 beforeEach 中,我将变量状态更改为 true,并且在调用 detectChanges() 之后
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
AppService,
{ provide: Router, useClass: RouterStub},
{ provide: HttpClient, useClass: HttpClientStub},
],
});
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
component.state = true;
fixture.detectChanges();
});
当我测试 btn 时未定义
it ('should increment by 1', () => {
const btn = fixture.debugElement.query(By.css('.myButton')).nativeElement;
// When I console.log(btn) here the btn is null because the state was false at begining;
btn.click();
fixture.detectChanges();
expect(component.counter).toBe(1);
});
解决方案
因此,如果有人想在 ngIf 隐藏时访问 html 中的某些内容,您应该在 TesteBed.configureTestingModule({declarations: [YourComponent]}) 中的声明中导入组件,就是这样。
推荐阅读
- php - 在 Wordpress 页脚中垂直对齐自定义创建的菜单
- amazon-web-services - Echo Spot 有时需要几分钟才能开始播放视频
- spring-boot - 如何对我的独立(非 Web 服务)应用程序进行 Spring 化?
- python - Python ping 脚本
- angular - 您如何访问 Angular 组件中的属性指令以获取规范?
- html - 哪个 div 的宽度是固定的?
- delphi - Delphi 7 到 XE8 分配二进制 ADO 参数值
- vbscript - MailItem.SentOn 在收件箱中的项目上生成 Object 不支持此属性或方法
- azure - USQL 日志记录、调试和故障排除
- node.js - *export ... from* 在带有打字稿的节点中返回未定义