This is a command that does not exist as a default command.
Cast the subject to another type. Will do nothing if the subject is already of that type.
Note: When using
.to()
you should be aware about how Cypress only retries the last command.
.to(type)
.to(type, options)
cy.wrap('00123').to('number'); // Yields 123
cy.wrap(42).to('string'); // Yields '42'
cy.wrap({ passive: 'Parakeet' }).to('string'); // Yields '{"passive":"Parakeet"}'
cy.wrap('Underwhelming Uakari').to('array'); // Yields ['Underwhelming Uakari']
cy.to('string'); // Errors, cannot be chained off 'cy'
cy.wrap('Dangerous dog').to('number'); // Errors, string can't be casted to number
> type (string)
The type you want to cast the subject to. Must be one of number
, string
or array
.
> options (Object)
Pass in an options object to change the default behavior of .to()
.
Option | Default | Description |
---|---|---|
timeout |
defaultCommandTimeout |
Time to wait for .to() to resolve before timing out |
log |
true |
Displays the command in the Command log |
.to('array')
yields an array.to('string')
yields a string or array of strings.to('number')
yields a number or array of numbers
// yields 42
cy.wrap('042').to('number');
// yields ['042']
cy.wrap('042').to('array');
Uses JSON.stringify
.
// yields '{"foo":"bar"}'
cy.wrap({ foo: 'bar' }).to('string');
// yields [ '123', '456', '789' ]
cy.wrap([123, 456, 789]).to('string');
When trying to cast to the type of the subject .to()
will do nothing.
// yields [ 'foo' ]
cy.wrap(['foo']).to('array');
Some commands, like .text()
, yield a string when there is only a single subject, but an array when
there are multiple subjects. You can use .to('array')
to ensure you can loop over the results of
.text()
without the risk of an error.
cy.get('.maybeOneElement')
.text()
.to('array')
.each((text) => {
// ...
});
.to()
requires being chained off a previous command.
.to()
will automatically retry itself until the subject can be casted..to()
will automatically retry itself until assertions you've chained all pass.
.to()
can time out waiting for a chained assertion to pass.
.to()
will output to the command log.