Hi folks I am new into cypress
I have a dropdown checkbox button from where I have to select multiple values at once
For this I have created a local function in type script as below
function calling
selectItems('Item 1','Item 4')
function definition
selectItems(value1: any, value2: any){
cy.get('dropdownlocator').click();
cy.get('dropdownlocatorCheckboxItems').contains(value1).click();
cy.get('dropdownlocatorCheckboxItems').contains(value2).click()
}
This is working fine but what I wanted is instead of doing the hard coding for each value I should make it so generic that if I pass single value in param it will work or if I pass more than 2 values it should also work
CodePudding user response:
There are two things that you can take a look at:
This is a hidden object of every function call, and can be used to figure out what arguments are passed in without defining what is passed in
selectItems() {
cy.wrap(arguments).each(value => {
cy.contains('dropdownlocatorCheckboxItems', value).click()
})
})
...
selectItems(value1)
selectItems(value1, value2)
This may cause trouble with the Typescript compiler, it's an older technique pre-typescript.
There is also Rest parameters
selectItems(...theValues) {
for (const value of theValues) {
cy.contains('dropdownlocatorCheckboxItems', value).click()
}
})
...
selectItems(value1)
selectItems(value1, value2)
Changing the parameter type to a string array is naïve.
You only shift the problem to the line before the function call
const selectItems(values: string[]) = {
...
})
const values = [value1, value2] // might as well just put these in the call params
selectItems(values)
CodePudding user response:
You can change the signature of your function to an array and use .forEach
to iterate through the array values.
const selectItems(values: string[]) = {
cy.get('dropdownlocator').click().then(() => {
// Add the forEach inside a .then to ensure it happens after you click the `dropdownlocator`
values.forEach((value) => {
cy.get('dropdownlocatorCheckboxItems').contains(value).click();
}
}
}
...
selectItems(['foo', 'bar', 'baz']);
selectItems(['foo']);