Cypress:如何正确关闭 mat-select

Kri*_*ris 3 automated-tests angular-material angular cypress

所以我使用 Cypress 来测试我们的 Angular 应用程序,但由于某种原因,我总是在关闭多选的 mat-select 组件时遇到问题。有没有人对此有好的解决方案?

function selectValue(id: string, value: string) {
    return cy.get(`mat-select[id="${id}"]`)
             .click()
             .then(() => 
                cy.get('mat-option')
                  .contains(value)
                  .click();
}
Run Code Online (Sandbox Code Playgroud)

小智 6

要关闭多选下拉列表中的列表,请执行用户操作并在列表外单击,例如在正文上

it('selects, closes, verifies', () => {

  cy.visit('https://material.angular.io/components/select/overview#multiple-selection')

  cy.get('div[role="listbox"]').should('not.exist')    // check list isn't open    

  cy.get('select-multiple-example').click()            // open
  cy.get('div[role="listbox"]').should('exist')        // check list is open    

  cy.contains('Extra cheese').click()                  // select an item
  cy.contains('Onion').click()                         // select an item
  cy.contains('Tomato').click()                        // select an item

  cy.get('body').click()                               // click outside the list

  cy.get('div[role="listbox"]').should('not.exist')    // check list isn't open    
  
  cy.get('select-multiple-example')
    .should('contain', 'Extra cheese, Onion, Tomato')  // verify
    
  cy.get('select-multiple-example')
    .should('not.contain', 'Mushroom')                 // verify contra
    
})
Run Code Online (Sandbox Code Playgroud)


Bat*_*u89 6

另一件对我有用的事情是

cy.get(`mat-select[data-testid="${dropdownTestId}"]`).focus().type('{esc}');
Run Code Online (Sandbox Code Playgroud)


Prz*_*ert 3

我建议这样的事情:

Cypress.Commands.add('selectValue', (value) => {
  cy
      .get('mat-select').first().click()
      .get('.mat-option-text').contains(value).click()
      .get('.mat-option-text').should('not.visible')
      .get('.mat-select-value-text').first().should(([{ innerText }]) => {
        expect(innerText).equal(value)
      })
});
Run Code Online (Sandbox Code Playgroud)

我在https://material.angular.io/components/select/overview上测试了它,它可以在我的本地计算机上运行。

如果出现问题,请随时提问