skip to Main Content

I’m testing my django server front-end with cypress. I should test the case where user selects empty string from options list. The code

//Next try to remove frequency    
cy.get('select').eq(5).find('option').contains('').then((selectOption) => {  
        cy.get('select').eq(5).select(selectOption.text());
}); 

led to error message:

cy.contains() cannot be passed an empty string 

although the empty string belongs to my choices:

html:

<select id="id_update_freq" calss ="form-control" name="update_freq"
    <option value="">""</option> 
    <option value="vk">Viikkotilasto</option>  
    <option value="kk">Kuukausitilasto</option> 
    <option value="nv">Kolmannesvuositilasto</option>
    <option value="kv">Puolivuositilasto</option>
    <option value="pv">Vuositilasto</option>
</select>

How can I test the case ?

2

Answers


  1. You should use select():

    Select an <option> within a <select>.

    describe('78120822', () => {
      it('should pass', () => {
        cy.get('#id_update_freq').select('');
        cy.get('#id_update_freq').should('have.value', '');
      });
    });
    
    Login or Signup to reply.
  2. One problem you have is the HTML has no <option> with empty string. The first option is the one you try to select, but it has two quotes in the string, so it’s not technically empty.

    So in your test this will pass

    cy.get('select').find('option').contains('""')
    

    But after fixing the typo,

    <select id="id_update_freq" calss ="form-control" name="update_freq">
    
      <option value=""></option>     <-- this is how an empty option looks
      ...
    
    </select>
    

    you can then select the empty option by using RegExp in the .contains() command

    cy.get('select')
      .find('option')
      .contains(/^$/)                     // regexp for empty string
      .should($emptyOption => {
        expect($emptyOption.index()).to.eq(0)      // passes
      })
    

    Of course, cy.select() works too :).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search