Получить предмет, когда скрыто с * ngIf в Angular для теста - PullRequest
0 голосов
/ 11 марта 2020

My 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);
});

Ответы [ 2 ]

0 голосов
/ 13 апреля 2020

Так что, если кто-то хочет получить доступ к чему-либо внутри html, когда он скрыт ngIf, вам следует импортировать ваш компонент в объявлениях внутри вашего TesteBed.configureTestingModule ({объявлений: [YourComponent]}), вот и все.

0 голосов
/ 11 марта 2020

Это должно работать. Я собирался написать это как комментарий, но мне нужно было пробел.

Попробуйте:

it ('should increment by 1', () => {
  console.log(component.state);
  fixture.detectChanges();
  console.log(component.state);
  expect(state).toBe(true);
  console.log(fixture.nativeElement);
  const button = fixture.nativeElement.querySelector('button.myButton');
  console.log(button);
});

Я отредактирую свой ответ, чтобы, надеюсь, получить то, что вы хотите. Можете ли вы сказать мне, что эти журналы выводят?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...