首页 > 解决方案 > 在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);
});

标签: angularjasmine

解决方案


因此,如果有人想在 ngIf 隐藏时访问 html 中的某些内容,您应该在 TesteBed.configureTestingModule({declarations: [YourComponent]}) 中的声明中导入组件,就是这样。


推荐阅读