Home > Blockchain >  How to test reactiveness of Vue Component in Cypress Componet tests
How to test reactiveness of Vue Component in Cypress Componet tests

Time:09-30

I am trying to test if a prop of a vue component is reactive using cypress component tests. Strangely it looks reactive, because my test is not even able to test if the original value was rendered as expected. Sadly it is not enough to test if the final value appears in the component, because in a RW the dependencies are so complicated, that I want to test chains of changes.

From my point of view it seems like cypress executes all the code of the test before the component is mounted and later waits on cy.get(...).contains, but nothing I did to delay this process (trying to wrap the change in a within statement, delaying it by wait or making the whole thing asynchronous) fixed the problem.

I cooked it down to the example given below.

This is my component:

<template>
  <div >
    <h1 data-cy="content">{{ content }}</h1>
  </div>
</template>

<script setup lang="ts">
import {computed} from 'vue'

const props = defineProps({
  object_prop: Object
})

const content = computed(() => {
  return String(props.object_prop.value);
})
</script>

This is the corresponding test:

import HelloWorld from './HelloWorld.vue'

describe('<HelloWorld />', () => {
    it('renders', () => {
        let data = {value: "Hello"}
        cy.mount(HelloWorld, {props: {object_prop: data}});
        cy.get('[data-cy="content"]').contains("Hello");
        data.value = "Bye";
        cy.get('[data-cy="content"]').contains("Bye");
    })
})

This is the cypress screenshot: enter image description here

Any suggestion is greatly appreciated.

CodePudding user response:

Could you try with using then?

describe('<HelloWorld />', () => {
    it('renders', () => {
        let data = {value: "Hello"}
        cy.mount(HelloWorld, {props: {object_prop: data}}).then((wrapper) => {
            component = wrapper;
        });
        cy.get('[data-cy="content"]').contains("Hello").should(() => {
            component.setProps({object_prop: {value: "Bye"}})
        })
        cy.get('[data-cy="content"]').contains("Bye");
    })
})

https://docs.cypress.io/api/commands/then

then will allow making the change after the getter or assertion finishes, so it will help the change execute in the correct order

  • Related