Skip
Skip

Reputation: 480

Cypress test if input field value has multiple lines

I want to check with a cypress test if the value is correct in a single-line text fields and multi-line text area.

I here have a single line box where I use the code down below to add an input:

cy.followLabel("When did the incident happen?").type("single \nline");

Same thing for the multi line text area

cy.followLabel("Deenter code herescribe what happened").type("multiple \nlines");

enter image description here

I tried to validate it with .should() but haven't found any chainers that would suit my need.

Is there something like .contains("\n")?

Upvotes: 0

Views: 5666

Answers (4)

Skip
Skip

Reputation: 480

I found a simpler solution. Just add should with the chainer "have.value" to your DOM element and then you are able to check for new lines.

.should('have.value','multiple\nlines');

Upvotes: 0

Paolo
Paolo

Reputation: 5461

Chai Assertion Library has a singleLine assertion in the chai-string module.

singleLine
assert.singleLine('abcdef');
expect('abcdef').to.be.singleLine();

To use assertions from other libraries, see Cypress recipe Adding Chai Assertions

Simple example

Install

yarn add -D chai-string

//or

npm install -D chai-string

Test

chai.use(require('chai-string'));

it('tests for singleLine', () => {

  cy.get('input')
    .type("single \nline")
    .invoke('val')
    .should('be.singleLine')  // passes

  cy.get('textarea')
    .type("multiple \nlines")
    .invoke('val')
    .should('not.be.singleLine')  // passes
})

enter image description here

Upvotes: 4

Alapan Das
Alapan Das

Reputation: 18626

You can directly check that the innerText has the new line character \n.

cy.get('selector').then(($ele) => {
  expect($ele).to.contain('\n')
})

In case your inner text doesn't have the newline characters, you assert the style tag containing overflow-wrap: break-word

cy.get('selector').should('have.attr', 'style').and('include', 'overflow-wrap: break-word')

Upvotes: 1

Sydney Y
Sydney Y

Reputation: 3152

I know there is an assertion "match" for regex.

match(RegExp)
Aliases: matches    
expect('testing').to.match(/^test/)

(from https://docs.cypress.io/guides/references/assertions)

So in your case the regex could be match(/.*\n.*/gm)

Upvotes: 2

Related Questions