1

I'm new to Cypress. I got the following error. assert expected <textarea.w-full.border-2.min-h-[100px].p-4> to have value "New message from user134", but the value was ' ' Any idea what the problem is?

This is the component that include the textarea

import { useRequest } from "@/context/requestContext";

const ChatUser = () => {
    const { requestData, setRequestData} = useRequest();

    return(
        <textarea 
            className='w-full border-2 min-h-[100px] p-4'
            value={requestData.text}
            data-cy="userChat"
            onChange={(e) => setRequestData({...requestData, text: e.target.value})}
            >
        </textarea>
    )
}

export default ChatUser;

I imported this component in the chat.tsx and I'm trying to test whole chat.tsx and my chat.cy.tsx is like that;

import React from 'react'
import Chat from './index';

describe('<Chat />',() => {
    it('mount', () => {
        cy.mount(<Chat />);
    });

    it('user chat textarea should work', () => {
        cy.mount(<Chat />);
        const newText = 'New message from user134';
        cy.get('[data-cy="userChat"]').type(newText);   
        cy.get('[data-cy="userChat"]').should('have.value', newText);
    })
})

enter image description here

idiltugba
  • 323
  • 1
  • 2
  • 10

2 Answers2

3

You syntax for useRequest() looks incorrect. Hooks generally return an array, not an object. If you have created the hook against convention, you should change it.

With this change, the test passes so either it's a typo or not reproducible.

const ChatUser = () => {
  const [requestData, setRequestData] = useRequest();
  ...

As well, you are testing a different component to the one shown. Probably it's a typo in your question.

Also, since it's component test you should probably clear() before type().

Aladin Spaz
  • 327
  • 6
2

Sometimes Cypress does not allow React hooks to complete an action. Since javascript is single-threaded, the test continues to process the next command before the app has completed the action (type command in this case).

Try adding a cy.wait(10) to get Cypress to relinquish the thread and allow useRequest to process the event.

cy.get('[data-cy="userChat"]').type(newText)
cy.wait(10) 
cy.get('[data-cy="userChat"]').should('have.value', newText)

Event shaping

The .type() command does fire a change event, but it does not add the value typed in (which is required by your event handler). Ref

You can be specific about the format of the event, here is an example - but likely you will need to play with the event constructor to get it right.

cy.get('[data-cy="userChat"]').type(newText)

cy.get('[data-cy="userChat"]')
  .then($textarea => {
    const changeEvent = new CustomEvent('change', {
      bubbles: true,
      detail: { text: newText },
    })
    $textarea[0].dispatchEvent(changeEvent)
  })

cy.wait(10) 
cy.get('[data-cy="userChat"]').should('have.value', newText)
Lola Ichingbola
  • 3,035
  • 3
  • 16