Conditional Rendering Not Working During Testing When Changing Props

I’m in the process of adding Vue to a server side (flask) rendered project and am not using single file components. I’ve started working on testing(mocha), but when testing conditional rendering (v-if), I am having issues with components responding to changes in props values.

In my test functions, I am calling wrapper.setProps(new value) followed by Vue.nextTick. It works when I set my value to true, but not when setting it to false. Below is example test code. Any thoughts? Thanks in advance.

require('jsdom-global')();
const assert = require('assert')
const Vue = require('vue');
const VueTestUtils = require('@vue/test-utils');

const App = Vue.component('app', {
    props: {
        showbutton:{
          required: false,
          type: Boolean,
        }
    },
    template: `
    <div>
      <myButton v-if="showbutton" ref="my-button"></myButton>
    </div>  
    `
  });

  const myButton = Vue.component('myButton', {
      template:`
      <div>
        <button type="button></button>
      </div>
      `
  });
  
let wrapper;

describe('testing myApp', function(){
    describe('myButton', function(){
      beforeEach(function(){
        console.log("setting up")
        wrapper=VueTestUtils.mount(App);
      });
      afterEach(function(){
        console.log("destroying")
        wrapper.destroy();
      });
      it('should not be visible when showButton is false', async function(){
        assert.equal(wrapper.contains({ref: 'my-button'}), false); // check that not rendered
        wrapper.setProps({showbutton:true}); // setting to true to illustrate issue
        await Vue.nextTick();
        assert.equal(wrapper.contains({ref: 'my-button'}), true); //works correctly
        wrapper.setProps({showbutton:false})
        await Vue.nextTick();
        assert.equal(wrapper.contains({ref: 'my-button'}), false); //fails
    });
  });
});

Hi

I think the problem could be that the ref still points to the myButton component even after it has been removed by the setting showButton to false. Maybe use one of these methods instead to see if myButton is on the page: https://lmiller1990.github.io/vue-testing-handbook/finding-elements-and-components.html#find-with-queryselector-syntax

Thank you. I didn’t realize the ref was still present even though the component was no longer being rendered. After switching my wrapper.find to referencing the component name, it worked.

1 Like