gpt4 book ai didi

Angular 应用程序在运行 cypress 测试时未检测到更改

转载 作者:行者123 更新时间:2023-12-05 07:16:16 25 4
gpt4 key购买 nike

在针对我的 Angular 应用程序运行 Cypress 测试时,我遇到了一个有趣的问题。

我看到的问题是,当我运行我的 cypress 测试时,DOM 没有响应来自 observables 或组件值的变化。

这是我所看到的一个非常简单的例子。

在我的组件中,我有以下内容。

组件.html

<button
mat-raised-button
color="primary"
(click)="toggleGemVersion()"
data-cy="serverspecs-hide-show-current-gem-version-btn">
Toggle Version
</button>

<div *ngIf="!hideGem">
<p data-cy="serverspecs-current-gem-version">{{ gemVersion$ | async }}</p>
</div>

组件.ts


hideGem = true;
gemVersion$: Observable<string> = this.store.pipe(select(getGemVersion));

toggleGemVersion() {
this.hideGem = !this.hideGem;
}

Cypress .spec.ts

it('should toggle the current gem version when the show/hide button is clicked', () => {
// Click the show/hide current gem version button
cy.get('[data-cy=serverspecs-hide-show-current-gem-version-btn]')
.should('be.visible')
.click();

// Cypress test fails here saying this element doesn't exist
cy.get('[data-cy=serverspecs-current-gem-version]')
.should('exist')
.should('have.value', '2.175.0');

// Click the show/hide current gem version button
cy.get('[data-cy=serverspecs-hide-show-current-gem-version-btn]')
.should('be.visible')
.click();

// Verify current gem version is not showing
cy.get('[data-cy=serverspecs-current-gem-version]').should('not.exist');
});

当我在 toggleGemVersion 函数中 console.log this.hideGem 的值时,我在 cypress 窗口中看到了正确的值控制台,但我没有看到这些更改反射(reflect)在 dom 中。

在运行 cypress 测试时,我需要在我的 Angular 配置中做些什么来让 DOM 发生变化吗?

另一个有趣的注意事项,我将 ChangeDetectorRef 服务暴露给 window 变量,当我运行 win.cd.detectChanges(); 时在 cypress click() 事件测试通过后进行 cypress 测试。

最佳答案

我遇到了同样的问题。在我的例子中,我为我的组件使用了 changeDetection: ChangeDetectionStrategy.OnPush 而没有使用 ChangeDetectorRef

要修复它,您必须将 ChangeDetectorRef 注入(inject)您的组件并更新您的 toggleGemVersion 方法:

toggleGemVersion() {
this.hideGem = !this.hideGem;
this.changeDetectorRef.detectChanges();
}

关于Angular 应用程序在运行 cypress 测试时未检测到更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59328311/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com