首页 > 解决方案 > 使用 Cypress 触发 Angular Ivy 变化检测

问题描述

我有以下赛普拉斯测试:

 ...

 describe('Form filling works properly, () => {
    it.only('should enable save button with correct form', () => {
      cy.get('input[name=notiName]').type('Test data for notiName, { force: true });
      cy.get('input[name=notiEnMessageName]').type('Test data for EnMessageName', { force: true 
    });

      cy.get('.navigationContainer [data-cy=btn-save]').should('be.enabled');
    });
  });

这工作得很好。

但是我在表单上有第三个输入值,它是一个复杂的数据选择器,我想用它来设置它的值,formControl而不是手动编程所有需要的点击。让我们暂时称其为formControl specialInputFormcontrol˙。

所以我这样做:

 describe('New notification works properly', () => {
    it.only('should enable save button with correct form', () => {
      cy.get('input[name=notiName]').type('Test data for notiName, { force: true });
      cy.get('input[name=notiEnMessageName]').type('Test data for EnMessageName', { force: true 

      let angular;
      cy.window()
        .then((win) => angular = win.ng)
        .then(() => cy.document())
        .then((doc) => {
          cy.log('Angular component captured');
          const componentInstance = angular
            .getComponent(doc.querySelector('my-component-name'));

          componentInstance.specialInputFormcontrol.setValue("special value");

           // change detection here?
        });

      cy.get('.navigationContainer [data-cy=btn-save]').should('be.enabled');
    });
  });

我的问题是,虽然值得到了更新,但由于 Angular 的引擎,我仍然需要强制更改检测刻度,以应用 cahnges。

我试图用以下代码代替该// change detection here?部分作为尝试:

  angular.applyChanges(componentInstance)

这将重置整个页面。

  angular.applyChanges(angular.getComponent($0);

$0 未定义。

   angular.probe(getAllAngularRootElements()[0]).injector.get(ng.coreTokens.ApplicationRef).tick()

angular.probe 在 Ivy 中不起作用。(角度 9 之后)

   componentInstance.injector.get(angular.coreTokens.ApplicationRef).tick();

“TypeError:无法读取未定义的属性‘get’”。

更新:

          ɵdetectChanges(componentInstance);

正如 ChrisY 指出的那样,在导入它之后我可以调用它,但是得到了TypeError: Cannot read property 'length' of null

如您所见,我查找了一些想法,但没有一个可行:(

标签: angularivy

解决方案


找到了解决方案 - 应该使用角度调试挂钩直接在组件引用上应用更改,如下所示:

describe('New notification works properly', () => {
    it.only('should enable save button with correct form', () => {
      cy.get('input[name=notiName]').type('Test data for notiName, { force: true });
      cy.get('input[name=notiEnMessageName]').type('Test data for EnMessageName', { force: true 

      let angular;
      cy.window()
        .then((win) => angular = win.ng)
        .then(() => cy.document())
        .then((doc) => {
          cy.log('Angular component captured');
          const componentInstance = angular
            .getComponent(doc.querySelector('my-component-name'));

          componentInstance.specialInputFormcontrol.setValue("special value");

          // Change detection trigger:
          angular.applyChanges(componentInstance)

        });

      cy.get('.navigationContainer [data-cy=btn-save]').should('be.enabled');
    });
  });

推荐阅读