首页 > 解决方案 > Vue3 计算属性仅在运行测试时才重新评估(通过 karma/jasmine)

问题描述

我正在尝试为具有业力/茉莉花的 Vue 3 组件的计算属性编写测试断言值。计算属性确实会发生变化,并在应用程序运行时不断被重新评估,但在测试中似乎没有被重新评估。下面是要测试的组件和测试本身的非常简化的代码:

// 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
    });
});

我在这里错过了什么吗?

标签: vue.jsjasminekarma-jasmine

解决方案


ref除非您传递属性或reactive对象 ,否则提供的值不是反应性的。见这里

所以我相信你可以通过几个小的调整让它工作。

// 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
    });
});

推荐阅读