Search code examples
typescriptcypress

Cypress add an option optionally


I have this case for example:

cy.get('input[type=file]').selectFile('myFile', {action: 'drag-drop', force: true})

In some cases i do not need to pass the option action and force.

How can i use the same command but add the options optionally please.

==== Edited Question

i want to put this in a command like below:

cypress.commands.add("selectMyFile", (myFile) => { cy.get('input[type=file]').selectFile(myFile) })

But in certain cases i want to use the same command but add the options to it.

Is there a possibility for calling my command like below:

cy.selectMyFile("myfile.jpg", {action: "drag-drop"})

Thank you


Solution

  • To transfer the options for .selectFile() to a custom command, add them as a parameter to the custom command.

    Cypress.Commands.add("selectMyFile", (myFile, options = {}) => {    
      cy.get('input[type=file]').selectFile(myFile, options) })
    })
    

    Using options = {} in the parameter list will allow the scenario where no options are passed in the test, in which case {} is an empty options object.

    Used:

    selectMyFile('my-file-name', {action: 'drag-drop'})
    

    To have some different default, say you want default drag-drop (the current default is select)

    Cypress.Commands.add("selectMyFile", (myFile, options = {}) => {    
    
      /*
        set whatever defaults you need in this object
        here I just set `force:true`, 
        but the others can be un-commented if desired
      */
      const defaultOptions = {
        force: true,
        // action: 'drag-drop',
        // log: false, 
        // timeout: 10000, 
      }
    
      /* 
        make actual options equal defaultOptions, 
        but override with any options values passed from the test
      */
      options = {
        ...defaultOptions,   
        ...options,
      }
      cy.get('input[type=file]').selectFile(myFile, options) 
    })
    

    Used:

    selectMyFile('my-file-name')   // action will be "drag-drop" since no option given
    
    selectMyFile('my-file-name', {action: 'select', force: true}) // give options