Home > Software engineering >  Vue3 computed property not re-evaluated only when running tests (via karma/jasmine)
Vue3 computed property not re-evaluated only when running tests (via karma/jasmine)

Time:10-09

I'm trying to write a test asserting value for a computed property for a Vue 3 component with karma/jasmine. The computed property does change and keeps being re-evaluated when the app is running, but does not seem to be re-evaluated in test. Below is a very simplified code for both the component to test and the test itself:

// Component to test
const Component1 = defineComponent({
  setup() {
    const someString = inject("someString");
    return { someString };
  },
  computed: {
    isSuccess(): boolean {
      return this.someString == "success";
    }
  }
});
export default Component1;

// Test
import "Component1" from "/path/to/component";
describe("Component1 tests", function() {
    let wrapper: VueWrapper<any>;
    let inTest: any;
    beforeEach(function(){
        wrapper = mount(Component1, {
            global: {
                provide: {
                    someString: 'failure'
                }
            }
        });
        inTest = wrapper.vm;
    });

    describe("isSuccess should return true if someString is 'success'", function(){
        expect(inTest.isSuccess).toBeFalse(); // this passes
        inTest.someString = 'success';
        expect(inTest.isSuccess).toBeTrue(); // but this fails
    });
});

Am I missing something here?

CodePudding user response:

Provided values are not reactive unless you pass a ref property or reactive object. See here.

So I believe you could get it to work with just a couple minor tweaks.

// Test
import { ref } from 'vue'
import "Component1" from "/path/to/component";
describe("Component1 tests", function() {
    let wrapper: VueWrapper<any>;
    let providedValue = ref('failure')
    let inTest: any;
    beforeEach(function(){
        wrapper = mount(Component1, {
            global: {
                provide: {
                    someString: providedValue
                }
            }
        });
        inTest = wrapper.vm;
    });

    describe("isSuccess should return true if someString is 'success'", function(){
        expect(inTest.isSuccess).toBeFalse(); // this passes
        providedValue.value = 'success';
        expect(inTest.isSuccess).toBeTrue(); // but this fails
    });
});
  • Related